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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With