如何从 Dart http 调用返回 json/如何完全使用流?

Gue*_*OCs 5 json http dart

这是我应该返回 json 的代码。我从这里改编了这段代码https://github.com/flutter/flutter/issues/15110

  Stream _defaultReturn(HttpClientResponse httpClientResponse) {
    Stream response = httpClientResponse.
                      transform(utf8.decoder).
                      transform(json.decoder).
                      asyncMap((json) => jsonDecode(json));
    return response;
  }

  Future<dynamic> get(String endpoint) async {
    HttpClientRequest httpClientRequest =
        await httpClient.getUrl(Uri.parse(_url + endpoint));
    _addCookies(httpClientRequest);
    final HttpClientResponse httpClientResponse =
        await httpClientRequest.close();
    return _defaultReturn(httpClientResponse);
  }
Run Code Online (Sandbox Code Playgroud)

我已经把返回类型Stream_defaultReturn,因为智能感知告诉我,巨人东西回来我Stream。我实际上想要接收一个 json(应该是一张地图)。我想我可能会消费或订阅此流以获得有用的东西。但是,我不认为 parsin json 作为流有用。在解析之前我不需要整个 json 吗?我不应该简单地将所有内容累积到 aString然后简单地调用jsonDecode吗?

从 http 调用返回 json 的最有效方法是什么?以及怎么做?

Sty*_*tyx 6

json.decoder将侦听源流并始终将其内容转换为一个 Object,因此您可以使用流的 返回它.first

Future<Object> get(String endpoint) async {
  var httpClientRequest = await httpClient.getUrl(Uri.parse(_url + endpoint));
  _addCookies(httpClientRequest);
  final httpClientResponse = await httpClientRequest.close();
  return httpClientResponse
           .transform(utf8.decoder)
           .transform(json.decoder)
           .first;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

var jsonObject = await myHttpClient.get(myEndpoint);
Run Code Online (Sandbox Code Playgroud)