Flutter FutureBuilder Example

In this article, we are going to learn how and when we can user flutter futurebuilder widget in flutter applications to perform asynchronous functions. You can also check out API related articles at HERE.

FutureBuilder widget is used to get current state of future objects. So we can display something particular for that state. Asynchronous functions are used to handle operations which take time to perform and return result after some time.

Flutter FutureBuilder widget calls future function to wait some time for result. As soon as it gets result it calls the builder functions where we make changes for UI. So we can manage our UI without any memory errors or deadlocks.

FutureBuilder widget is stateful widget by default. FutureBuilder is used to check connectionstate. So we can display particular UI like indicator or something while our future is busy. There are three types of connectionstates.

ConnectionState.none : In this state, future is null. initialData is used as default value until future is completed.

ConnectionState.waiting : In this state, future is not null and future is not completed.

ConnectionState.done : In this state, future is not null and future is completed. At the time of completion of future we get result form two options: success and fail. If AsyncSnapshot.hasData is true and future is completed successfully, we display our data in UI. If AsyncSnapshot.hasError is true then we can display error related UI to users.

FutureBuilder(
Key key,
this.future,
this.initialData,
@required this.builder,
)
 
 

Fetch Data from API

Future> getUsers() async {
final response =
await http.get(‘https://jsonplaceholder.typicode.com/users’);
if (response.statusCode == 200) {
var getUsersData = json.decode(response.body) as List;
var listUsers = getUsersData.map((i) => User.fromJSON(i)).toList();
return listUsers;
} else {
throw Exception(‘Failed to load users’);
}
}
 
 

Flutter FutureBuilder

Scaffold(
body: FutureBuilder<List<User>>(
future: listUsers,
builder: (context, snapshot) {
if (snapshot.hasData) {
// display data
} else if (snapshot.hasError) {
return Center(
child: Text(“${snapshot.error}”),
);
}
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.cyanAccent,
),
);
},
));
 
 
 
flutter futurebuilder
 

Leave a Reply