Thursday, November 29, 2018

Flutter making network calls

For making network calls, the below package can be imported

import 'package:http/http.dart' as http;

Dart apps are single-threaded, but Dart provides support for running code on other threads as well as running asynchronous code that does not block the UI thread using an async/await pattern.

To keep the list of list of members at the class level, below to be done

var members = [];

The underscores at the beginning of the names make the members of the class private.
Below is how to make an asynchronous HTTP call

_loadData() async {

String dataURL = "https://urltoetchthedata.com";
http.response = await.http.get(dataURL);
setState((){
_members = JSON.decode(response.body);
});

}

The async keyword onto _loadData() to tell Dart that it’s asynchronous, and also the await keyword on the http.get() call that is blocking.
When the HTTP call completes, you pass a callback to setState() that runs synchronously on the UI thread. In this case, you are decoding the JSON response and assigning it to the _members list.


References:
https://www.raywenderlich.com/116-getting-started-with-flutter

No comments:

Post a Comment