This article is about a very useful widget of Flutter, the Future builder widget.
When you want to show some async function result on a widget you will face some troubles because a widget’s build sync method will not wait while fetching data. Flutter provides a better answer to this question. It is the Future Builder widget.
This is the asynchronous function I used to explain how the Future Builder widget works. This function simply returns a String object.
The below codes show a builder function and how we can use the FutureBuilder widget to show the data returns by the above code.
In this example, the future function getUserName() is called in the future. When this method returns data, the userNameSnapshot object’s connection state will be equal to ConnectionState.done and the builder will return the text widget.
There are three connection states of AsyncSnapshot.
Here I showed one way of handling async function results using the Future Builder widget. There is another method to handle this using the states(hasData and hasError) of AsyncSnapshot.
We can use hasData and hasError states of AsyncSnapshot to handle the Future Builder widget.
Basically userNameSnapshot.hasData returns true when AsyncSnapshot is with data and otherwise, it returns false, userNameSnapshot.hasErrorreturns true when AsyncSnapshot is with error(s) or else it returns false.
Likewise, we can use these two methods to show async function results on widgets.