首页 > 解决方案 > 如何在 Dart 中发出网络请求并返回一个 json 对象

问题描述

发出网络请求对 Python 来说很容易,而让这个请求变得容易的是那个sync请求。

在 Dart 中,我可以提出这样的请求:

HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://www.example.com/"))
    .then((HttpClientRequest request) {
    // Optionally set up headers...
    // Optionally write to the request object...
    // Then call close.
    ...
    return request.close();
    })
    .then((HttpClientResponse response) {
    // Process the response.
    ...
    });

显然这是异步请求。在我看来,上面的代码可以重复使用很多次。所以我想发出一个请求并返回一个 JSON 对象。

getResponse(String url) async {
    HttpClient httpClient = new HttpClient();
    HttpClientRequest request = await httpClient.getUrl(Uri.parse(url));
    HttpClientResponse response = await request.close();
    String responseBody = await response.transform(utf8.decoder).join();
    Map jsonResponse = jsonDecode(responseBody) as Map;
    httpClient.close();
    return jsonResponse;
}

如您所见,上述方法getResponse返回Future<dynamic>. 那么如何调用它并获取 json 值呢?

标签: dartflutter

解决方案


要从 Future 内部获取动态,请执行以下操作之一:

  // option 1 async method
  MyAsyncMethod() async {
    dynamic result = await getResponse("http://google.com");
    if (result is Map) {
      // process the data
    } 
  }

  // option 2 callback with .then()
  MyNonAsyncMethod() {
    getResponse("http://google.com").then ( (dynamic result) {
      if (result is Map) {
        // process the data
      }   
    });
  }

请注意,您自己的异步方法也可以返回 aFuture<something>并在调用时以相同的两种方式处理。

其中 map 是嵌套的Map<String, Dynamic>,而 result 是您创建的符合 Json 序列化接口的类型的对象(请参阅此链接)。

要访问地图中的数据:

  //given example json structure
  var map = {
    "myPropertyName":50,
    "myArrayProperty":[
      "anArrayEntry"
    ],
    "mySubobject": {
      "subObjectProperty":"someValue"
    }
  };

  var myProperty = map["myPropertyName"]; // get a property value from the object
  var myArrayEntry = map["myArrayProperty"][0]; // get first element of an array property
  var mySubobjectPropertyValue = map["mySubobject"]["subObjectProperty"]; // get a property value from a subobject

推荐阅读