dart - 如何在 Dart 中发出网络请求并返回一个 json 对象

标签 dart flutter

对 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 值呢?

最佳答案

要从 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
      }   
    });
  }

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

其中 map 是嵌套的 Map<String, Dynamic>并且 result 是您创建的符合 Json 序列化接口(interface)的类型的对象(参见 link)。

访问 map 中的数据:

  //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

关于dart - 如何在 Dart 中发出网络请求并返回一个 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54158508/

相关文章:

flutter - 如何完全删除 Dart ubuntu?

flutter - dart/flutter pub 的 credentials.json 的新位置是什么

flutter - 如何在文本字段中添加图标

Android Studio 代码建议不适用于 Flutter

flutter - 如何在 flutter 中从 JSON 文件中获取数据

flutter - 有没有办法在全屏模式下以抖动的方式播放视频?

macos - ObjectBox Flutter MacOS

android - 使用唯一标识符flutter/android识别设备

json - 如何在Dart中创建特定类型的嵌套JSON数据?

flutter - 如何在 Flutter 中裁剪 WebView 的大小?