首页 > 解决方案 > Flutter web - 调用 http.get 抛出异常

问题描述

这在 Android/桌面上运行良好:

Future<List<City>> fetchCities() async {


  final response =
  await http.get(globals.url + '/city',
      headers: {HttpHeaders.acceptHeader: globals.apiVersion});

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return compute(parseCities, response.body);
  } else {
    // If that call was not successful, throw an error.
    print('Failed to load cities');
    throw TextException(Strings.msg_session_expired);
  }
}

但是当作为 Web 应用程序启动时,我遇到了一个异常:

errors.dart:145 Uncaught (in promise) Error: Unsupported operation: Platform._version
    at Object.throw_ [as throw] (errors.dart:194)
    at Function._version (io_patch.dart:284)
    at Function.get version [as version] (platform_impl.dart:121)
    at get _version (platform.dart:74)
    at Function.desc.get [as _version] (utils.dart:75)
    at Function.get version [as version] (platform.dart:231)
    at Object._getHttpVersion (http_impl.dart:3234)
    at new _http._HttpClient.new (http_impl.dart:2071)
    at Function.new (http.dart:1473)
    at new io_client.IOClient.new (io_client.dart:23)
    at Function.new (client.dart:30)
    at _withClient (http.dart:165)
    at _withClient.next (<anonymous>)
    at runBody (async_patch.dart:84)
    at Object._async [as async] (async_patch.dart:123)
    at Object._withClient (http.dart:164)
    at Object.get (http.dart:47)
    at fetchCities (mcity.dart:113)
    at fetchCities.next (<anonymous>)
    at runBody (async_patch.dart:84)
    at Object._async [as async] (async_patch.dart:123)

是否有任何方法可以使 http.get 请求在 flutter_web 上工作?

标签: exceptiondarthttp-getflutter-web

解决方案


的使用HttpHeaders.acceptHeader可能是问题所在。它是dart:io库的一部分,没有为 Flutter Web 启用。您应该尝试以不同的方式设置标题。例如,基于这个常数值,下面东西应该可以工作。

final response =
  await http.get(globals.url + '/city',
      headers: {"accept": globals.apiVersion});

在另一篇文章中,我使用了http包,表明该包可用于 Flutter Web。


推荐阅读