Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

dart

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?

like image 453
CoXier Avatar asked Jan 12 '19 10:01

CoXier


People also ask

Can we return a JSON in GET request?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.

Can you send JSON directly over a network?

JavaScript can send network requests to the server and load JSON. JS does this using something called AJAX. AJAX stands for Asynchronous JavaScript and XML. JS has an API, fetch, to GET(receive) and POST(send) information to the server.


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
like image 59
Oswin Noetzelmann Avatar answered Sep 24 '22 16:09

Oswin Noetzelmann