![]() |
VOOZH | about |
In Flutter, the FutureBuilder Widget is used to create widgets based on the latest snapshot of interaction with a Future. It is necessary for Future to be obtained earlier either through a change of state or change in dependencies. FutureBuilder is a Widget that will help you to execute some asynchronous function and based on that function's result your UI will update.
FutureBuilder is Stateful by nature i.e it maintains its own state as we do in StatefulWidgets.
Syntax:
FutureBuilder( Key key, this.future, this.initialData, @required this.builder, ) And, builder should not be null.
When we use the FutureBuilder widget we need to check for future state i.e future is resolved or not and so on. There is various State as follows:
We will create FutureBuilder Widget in a step by step manner.
Step 1: Create a future that needs to be resolved.
The above snippet is to demonstrate a real network call. We have used a 2 seconds delay.
Step 2: Create a FutureBuilder Widget and manage the waiting state.
In this snippet, we can see we are returning a LoadingSpinner. It will only be displayed when the future is in the Waiting state.
Step 3: Manage Future done state i.e when the future is resolved. This step also requires checking for any error that could occur during a network call.
In the above snippet, you can see we are checking
snapshot.hasError This step is require because it could be possible that future is resolved but an error has occurred.
We are also checking
snapshot.hasData This step is required because it may be possible that future is resolved but nothing is returned due to some reasons, so always perform these checks otherwise you may get unexpected behaviour.
Complete Source Code:
Output: