FutureBuilder Widget ConnectionState key Points

FutureBuilder

Flutter and Dart are asynchronous by nature. With Dart's Future, you can manage IO without worrying about threads or deadlocks.


FutureBuilder

But how do you build widgets when a Future is involved?

FutureBuilder lets you easily determines the current state of a future and choose what to show while the data's loading and when it is available.

Start by giving FutureBuilder a future, and then a builder. But make sure to check the state of the future with connectionState and display an appropriate widget when your future is busy.

Finally, it is good practice to check that no error has occurred while your future was resolving.

Key points on ConnectionStates

There are other ConnectionStates that you can use.

ConnectionState.none;
ConnectionState.waiting;
ConnectionState.done;

ConnectionState.none : In this state future is null.The [AsyncSnapshot.data] will be set to [initialData] unless a future has already completed, in which case the previous result holds on.

ConnectionState.waiting : [future] isn't null, but has not however completed. The [AsyncSnapshot.data] will be set to [initialData] unless a future has already completed, in which case the previous result holds on.

ConnectionState.done : [future] isn't null, and has completed. In case the future completed successfully, the [AsyncSnapshot.data] will be set to the value to which the future completed. If it completed with an error, [AsyncSnapshot.hasError] will be true and [AsyncSnapshot.error] will be set to the error object.

Source Code for the FutureBuilder Widget

So, to get better understanding, let's take an example of FutureBuilder Widget.


Result of the above program :

Bravo! Here we can make our application working fine.



Previous
Next Post »