小编典典

如何在Flutter中使用Dart http包指向localhost:8000?

flutter

我正在遵循Flutter Networking /
HTTP教程
对运行在localhost:8000上的服务器进行GET请求。通过浏览器访问我的本地主机可以正常工作。我的代码如下所示:

var url = 'http://localhost:8000';
Future<String> getUnits(String category) async {
    var response = await httpClient.get('$url/$category');
    return response.body;
}

当我指向任何真实的网址(例如)时,此方法工作正常https://example.com,但是当我指向https://localhost:8000https://localhost(或它们的任何变体)时,出现以下错误:

E/flutter ( 4879): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter ( 4879): SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 47060
E/flutter ( 4879): #0      IOClient.send (package:http/src/io_client.dart:30:23)

每次我重新加载应用程序时,上述错误中的端口都会更改。我查看了http程序包代码,似乎没有一种方法可以指定URL的端口。我如何指向我的本地主机?


阅读 793

收藏
2020-08-13

共1个答案

小编典典

简短答案:您可以传递Uri而不是字符串作为参数

      var client = createHttpClient();
      client.get(new Uri.http("locahost:8000", "/category"));
2020-08-13