如何使用http包异步从flutter中的API读取传入流?

问题描述 投票:0回答:2

我正在开发一个 Flutter 应用程序,该应用程序需要从 API 作为流接收数据,并在收到数据后立即处理每个数据块。我的 API 以块的形式发送数据,我想在 Flutter 应用程序中读取这些数据并在块值到达时打印它们。

我尝试使用

http
包发出请求,但我不确定如何监听传入流并实时处理分块数据。这是我当前的代码:

import 'package:http/http.dart' as http;

void fetchData() async {
  final url = Uri.parse('http://my-api-server.com/stream');
  final client = http.Client();

  try {
    final request = http.Request('GET', url);
    final response = await client.send(request);

    // How to read and print the chunks from the response stream?
  } catch (e) {
    print("Error: $e");
  } finally {
    client.close();
  }
}

如何修改此代码以侦听传入流、处理收到的每个块并实时打印块值?任何帮助将不胜感激。

flutter dart http stream
2个回答
1
投票

要监听传入流并处理 Flutter 中收到的每个数据块,您可以利用 http 包的 Stream 属性。您可以通过以下方式修改代码来实现此目的:

解决方案代码:

import 'package:http/http.dart' as http;
import 'dart:convert';

void fetchData() async {
  final url = Uri.parse('http://my-api-server.com/stream');
  final client = http.Client();

  try {
    final request = http.Request('GET', url);
    final response = await client.send(request);

    // Read and print the chunks from the response stream
    await for (var chunk in response.stream.transform(utf8.decoder)) {
      // Process each chunk as it is received
      print(chunk);
    }
  } catch (e) {
    print("Error: $e");
  } finally {
    client.close();
  }
}

在此代码中,我们使用 http.Response 对象的 Stream 属性,并使用 utf8.decoder 对其进行转换,以将传入的字节转换为可读的字符串。

通过使用await for 循环,我们可以在块实时到达时对其进行迭代。在此示例中,将使用 print(chunk) 处理和打印每个块。您可以将 print(chunk) 行替换为处理数据所需的逻辑。

记住导入 dart:convert 包以访问 utf8.decoder 来解码传入的流。

通过这些修改,您的 Flutter 应用程序将能够从 API 接收分块数据,并在数据到达时对其进行处理。

希望有帮助,让我知道您的反馈,谢谢,快乐编码..


0
投票

fread fwrite你可以把文件当作大数据,用pyton或者Visual Basic或者.net,你需要建立一个缓冲区

© www.soinside.com 2019 - 2024. All rights reserved.