How to make a network request and return a json object in Dart

Viewed 3238

Making a network request is easy to Python and what makes it easy is that sync request.

In Dart, I can make a request like this:

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.
    ...
    });

Obviously it's async request. In my opinion, above code can be reused many times. So I want to make a request and return a JSON object.

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;
}

As you see, the above method getResponse returns Future<dynamic>. So how can I call it and get the json value?

1 Answers

To get the dynamic from inside the Future you do one of the following:

  // 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
      }   
    });
  }

Note that your own async method can also return a Future<something> and be treated in the same two ways when called.

Where map is a nested Map<String, Dynamic> and result is an object of type of your creation that conforms to Json serialization interface (See this link).

To access Data in the 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
Related