Futures in a widget
Learning objectives
- You know how to the FutureBuilder widget.
In the previous part, clicking the button retrieves a joke from the API, waiting for the data from the API. Flutter also provides a widget called FutureBuilder that can be used to communicate progress on asynchronous tasks to the user.
FutureBuilder
FutureBuilder
takes two arguments, a Future
and an AsyncWidgetBuilder. While the Future
is the same as what we have also used previously, the AsyncWidgetBuilder
takes a BuildContext and an AsyncSnapshot, and returns a widget. Whenever the state of the future changes, the widget is re-created.
The AsyncSnapshot has a handful of properties that are of interest to us. The property connectionState has information on the state of the asynchronous operation, the property hasData provides information on whether the processing has completed and whether data is available, the property hasError provides information on whether there were errors in the processing, the property error with error information, and the property data provides access to the actual data.
An example of a FutureBuilder
that waits for a Future<String>
could look as follows.
// Future<String> _data = ...
FutureBuilder<String>(
future: _data,
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Text("Waiting for data.");
} else if (snapshot.hasError) {
return Text("Error: ${snapshot.error}");
} else if (!snapshot.hasData) {
return Text("No data yet.");
} else {
String content = snapshot.data!;
return Text("Here you go: $content");
}
},
);
A whole application, in turn, using the FutureBuilder
could work as follows. In the following example, there is an asynchronous function performOperation
that takes a while to complete. The FutureBuilder
is used to display a widget that shows both changes in the processing as well as the outcome of the processing. Try the application out.
Flutter also provides a few progress indicators, including CircularProgressIndicator that can be used to visually show that something is being waited on.
Progress indicators and testing
The tests in this course wait for changes in the user interface and then check for outcomes. The progress indicators provide constant changes in the user interface and can cause problems to the tests. When returning applications for assessment, do not use progress indicators or other animations that continuously update what is shown.
FutureBuilder and APIs
When working with APIs, the main change in the use of the FutureBuilder
is that we wait for data from an API. In the following example, we outline an application that uses the Joke API and FutureBuilder
. Note that in the following example, the JokeService has a 3 second delay and a 30% chance of throwing an error, added to demonstrate the capability of FutureBuilder
to highlight errors.