How to get data from async function to show on a widget.

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 Future Builder widget to show the data returns by the above code.

Method 1 (using connection states)

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 .

  1. ConnectionState.noneNot currently connected to any asynchronous computation. For example, a FutureBuilder whose FutureBuilder.future is null.
  2. ConnectionState.waitingConnected to an asynchronous computation and awaiting interaction.
  3. ConnectionState.doneConnected to a terminated asynchronous computation.

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 .

Method 2 (using hasData and hasError states)

We can use hasData and hasError states of AsyncSnapsot 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 AsyncSnapsho is with error(s) or else it returns false.

Likewise, we can use these two methods to show async function results on widgets.

Computer Science and Engineering Undergraduate at University of Moratuwa, Sri Lanka