We are going to read about FutureBuilder, which help us to use futures in the flutter applications.

If you don’t know about futures, I encourage you to read about it in our blog post

To use a future in your flutter application, you need to use a class called FutureBuilder. This is a class which rebuilds itself when the future value changes.

Let’s take a look at an example

This is a news app! When use press is the button, the application goes and fetches some news and show it. As we know, fetching something from internet takes time. That is why we need a to use a future

Because we cannot actually reach out to internet from dart pad ( which is the tool we use to show you the running code snippet), we simulate the fetching process. We have a method which returns a Future<String> using delayed method.

Future<String> getNews() {
  return Future<String>.delayed(const Duration(seconds: 3), () async => 'It is getting WARMER!');
}

Now, in the state of the class, we have a state variable with type Future<String>?. This is the future we are going to populate by calling our news fetcher method.

When the Fetch button pressed, we are going to () => setState(() { news = getNews(); }), which changes the state, and assigning the result of getNews to state variable.

Now, for the actual widget. FutureBuilder looking at that class and changes what it renders accordingly

FutureBuilder(
              future: news,
              builder: (context, snapshot) {
                if(snapshot.hasData && snapshot.data != null) {
                  return Text( snapshot.data!);
                } else if(snapshot.hasError) {
                  return Text('Error fetching news: ${snapshot.error.toString()}');
                } else {
                  return const CircularProgressIndicator();
                }
              })

Let’s note that snapshot var is of type AsyncSnapshot which basically represents what is the status of the future.

If snapshot does not have any data, which means it is not finished yet, we render a wait circle. Otherwise, we render snapshot’s data property, which in this case is a text, or an error depending on the outcome of the future.