Flutter 应用程序/stream+json Content-Type

Stu*_*ukz 5 json http dart flutter reactive

我正在尝试使用内容类型在 flutter 中进行 Http 客户端调用:application/stream+json 并接受:application/stream+json,以便使用来自后端的反应式响应,但这就是响应的样子:

{"name":"bobby", "lastname": "fisher"}
{"name":"dominic", "lastname": "thiem"}
{"name":"roger", "lastname": "federer"}
{"name":"a", "lastname": "b"}
{"name":"c", "lastname": "d"}
{"name":"e", "lastname": "f"}
Run Code Online (Sandbox Code Playgroud)

没有 [ ] 和 ,那么我如何迭代它呢?

PD:如果我发送 application/json 可以工作,但不能以反应方式发送。

有什么帮助吗?

iCo*_*ime 2

因此,我们需要在这里采取两个步骤:

  1. 从网络获取原始字节流
  2. 将该流转换为 json 流

使用dio,我们可以得到这样的流:

final response = await dio.get<ResponseBody>(
  '/streaming/url',
  options: Options(
    responseType: ResponseType.stream,
  ),
);

// Check status code, etc...

final responseStream = response.data!.stream;
Run Code Online (Sandbox Code Playgroud)

一旦我们有了流,我们需要将其解码为文本,按行分割,并解析 json。无论您是否使用,这部分都是相同的dio

utf8.decoder
    .bind(responseStream)
    .transform(const LineSplitter())
    .map((line) => jsonDecode(line));
Run Code Online (Sandbox Code Playgroud)

所以,最终的方法可能看起来像这样

Stream<dynamic> subscribeToStream() async* {
  final response = await dio.get<ResponseBody>(
    '/streaming/url',
    options: Options(
      responseType: ResponseType.stream,
    ),
  );

  // check status, etc

  yield* utf8.decoder
      .bind(response.data!.stream)
      .transform(const LineSplitter())
      .map((line) => jsonDecode(line));
}
Run Code Online (Sandbox Code Playgroud)