Sub topic 4
Rendering a Future with FutureBuilder
This chapter assumes you know Dart async, await, and Future, plus Flutter StatefulWidget, build, initState, dispose, and setState. You will use those pieces to render a screen while an asynchronous operation is running.
A Future<T> represents one value that will be available later. It completes either with a value of type T or with an error. FutureBuilder<T> listens to that future and rebuilds part of the widget tree when the future changes state.
The FutureBuilder working model
FutureBuilder has two important inputs:
future: the asynchronous operation to observe.builder: a function that receives the currentAsyncSnapshot<T>and returns a widget.
An AsyncSnapshot is a description of the latest state observed by the builder. Its most useful properties are:
connectionState: whether the future is waiting, active, done, or has no connection.data: the successful result, if one exists.error: the error, if the future failed.hasDataandhasError: convenient checks for the previous two properties.
For a normal Future, the important connection states are waiting and done.
A builder can render these states as follows:
| Future state | Snapshot information | Typical UI |
|---|---|---|
| Waiting | `connectionState == waiting` | Progress indicator |
| Success | `hasData` and `connectionState == done` | Result content |
| Failure | `hasError` and `connectionState == done` | Error message and retry action |
The builder may run more often than the future completes because its parent can rebuild. The builder must therefore be a pure description of the current snapshot. Do not put one-time work inside it.
A complete FutureBuilder example
The following widget loads a name, displays a progress indicator while waiting, and handles both success and failure:
import 'package:flutter/material.dart';
class UserGreeting extends StatefulWidget {
const UserGreeting({super.key});
@override
State<UserGreeting> createState() => _UserGreetingState();
}
class _UserGreetingState extends State<UserGreeting> {
late final Future<String> _name;
@override
void initState() {
super.initState();
_name = _fetchName();
}
Future<String> _fetchName() async {
await Future<void>.delayed(const Duration(seconds: 1));
return 'Ada';
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _name,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
return Text('Hello, ${snapshot.data}');
},
);
}
}The generic type String connects the future's result type to the snapshot's data type. In this example, snapshot.data is a String?, so Dart treats it as potentially null. Because the future completes with a string, the final branch can safely display it in this controlled example.
Checking hasError first prevents an error state from being mistaken for normal loading. Checking connectionState next makes the loading state explicit. You can also use snapshot.hasData, especially when a successful future can return a nullable value or when the UI needs to distinguish missing data from an empty result.
Keep the Future stable
Create the future in initState, a field initializer, or another event such as a refresh callback. Do not call the asynchronous method directly in build.
// Anti-pattern: this creates a new Future on every rebuild.
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _fetchName(),
builder: (context, snapshot) {
return Text(snapshot.data ?? 'Loading...');
},
);
}When build runs again, _fetchName() returns a new future. FutureBuilder sees a different future, subscribes to it, and starts the operation again. This can cause repeated network requests, repeated side effects, and a loading indicator that never settles.
If a parent supplies the future through a widget property, compare the new property in didUpdateWidget when you need to react to a changed input. For a locally owned request, storing it in State is usually enough.
Exercise
Where should a Future normally be created when a StatefulWidget loads data once, and why?
Show answer
Create it in initState and store it in a State field. This keeps the same Future across ordinary rebuilds and prevents the asynchronous operation from restarting.