Sub topic 4
Rendering a Future with FutureBuilder
This chapter assumes you know Dart's async/await and Future, and the difference between StatelessWidget and StatefulWidget. It also assumes you are comfortable with setState, initState, and dispose. You should already have met AsyncSnapshot and ConnectionState. Here they are used in practice.
What FutureBuilder does
A Future<T> completes once, later, with a value or an error. A widget's build method must return a widget immediately and cannot wait. FutureBuilder<T> connects the two. It listens to a Future, stores the latest AsyncSnapshot<T>, and calls your builder function each time that snapshot changes. You describe the UI for each snapshot, and Flutter handles the subscription and the rebuild.
FutureBuilder is a StatefulWidget. Its State holds the snapshot, so you never call setState for the async result yourself.
The constructor
| Parameter | Type | Meaning |
|---|---|---|
| `future` | `Future<T>?` | The computation to observe. `null` means "nothing to wait for". |
| `builder` | `AsyncWidgetBuilder<T>` | A function `(BuildContext, AsyncSnapshot<T>) => Widget`. It must not return `null`. |
| `initialData` | `T?` | A value to put in the first snapshot, so the first frame can show it before the `Future` completes. |
Only builder is required. initialData is covered more fully in the StreamBuilder chapters, where it matters more.
A complete example
The widget below fetches a name once and renders one of three things: a spinner, an error message, or a greeting. The Future is created in initState and stored in the State object. Section "Why the Future must be stable" explains why that matters.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(
home: Scaffold(body: Center(child: UserGreeting())),
),
);
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.hasData) {
return Text('Hello, ${snapshot.data}');
}
return const CircularProgressIndicator();
},
);
}
}Run it and you see a spinner for one second, then "Hello, Ada". The builder function runs at least twice: once with no data, and again after the Future completes.
How it works internally
Knowing what FutureBuilder does behind the scenes explains most of its quirks.
- Subscribe in
initState. TheStateobject stores an initial snapshot. IfinitialDatais given, the snapshot holds it. Otherwise the snapshot has no data and the statenone. Iffutureis not null, theStatecallsfuture.then(...)and moves the snapshot towaiting. - First build. The builder runs with the
waitingsnapshot. This happens even if theFutureis already complete, becausethencallbacks run asynchronously, after the current frame is built. - Completion. When the
Futurecompletes, the callback callssetStatewith a new snapshot in thedonestate. That snapshot holds either the data or the error. The builder runs again. - Parent rebuilds. When the parent rebuilds and passes a
FutureBuilderconfiguration,didUpdateWidgetcomparesoldWidget.futurewithwidget.futureusing identity. If they are the same object, nothing happens and the builder simply runs with the current snapshot. If they differ, the old subscription is dropped and the newFutureis subscribed to. - Dispose.
FutureBuildercannot cancel aFuture, because DartFutures have no cancellation. It ignores the result instead. A callback from aFuturethat has been replaced or disposed does nothing.
ConnectionState for a Future
ConnectionState has four values, but a FutureBuilder uses only three.
| Value | When it occurs |
|---|---|
| `none` | The `future` is `null` and nothing is being awaited. |
| `waiting` | A `Future` is subscribed and has not completed. |
| `active` | Never used by `FutureBuilder`. It belongs to streams that have emitted events and may emit more. |
| `done` | The `Future` has completed with a value or an error. |
A common mistake is to write a branch for active in a FutureBuilder. It will never run.
Choosing what to check
The snapshot offers several getters. Their meanings differ in subtle ways.
hasDataistruewhen the snapshot holds a non-null value.hasErroristruewhen the snapshot holds an error.connectionStatetells you where the snapshot is in its lifecycle.dataisT?, andrequireDatareturnsTand throws if there is no data.errorisObject?, andstackTraceis available for errors.
Check the error first
A snapshot can have an error and also keep older data (see below). If you check hasData first, you may show stale data and hide a failure. Test hasError before hasData, as the example does.
Beware of nullable results and Future<void>
hasData is false when a Future completes with null. That breaks a builder that equates "no data" with "still loading". The same thing happens with Future<void>, which never produces data. For these cases, test connectionState instead.
import 'package:flutter/material.dart';
class NicknameLabel extends StatefulWidget {
const NicknameLabel({super.key});
@override
State<NicknameLabel> createState() => _NicknameLabelState();
}
class _NicknameLabelState extends State<NicknameLabel> {
late final Future<String?> _nickname;
@override
void initState() {
super.initState();
_nickname = Future<String?>.delayed(
const Duration(milliseconds: 500),
() => null, // this user has no nickname
);
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String?>(
future: _nickname,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
final nickname = snapshot.data;
return Text(nickname ?? 'No nickname set');
},
);
}
}If this builder tested hasData instead, a user with no nickname would see a spinner forever.
The connectionState != done check gives a reliable "still loading" test. Combined with the error check, everything that follows is a completed, non-error result.
Errors surface in the snapshot
An error thrown inside the Future does not crash the build. It arrives as snapshot.error. If you never check hasError, the failure is invisible and the builder falls through to its default branch. The next chapter covers designing the loading, error, and data states in detail.
Why the Future must be stable
The future property is compared by identity on every parent rebuild. Writing future: _fetchName() directly in build creates a new Future object each time build runs, so didUpdateWidget sees a different object. It unsubscribes, subscribes to the new request, and goes back to waiting.
// Anti-pattern: a new Future starts on every rebuild.
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _fetchName(), // called again whenever build runs
builder: (context, snapshot) {
// The snapshot resets to waiting each time the Future changes.
return Text(snapshot.data ?? 'Loading...');
},
);
}Any rebuild can trigger this: a parent calling setState, a theme change, a keyboard opening, or an animation ticking. The symptoms are repeated network requests, flickering spinners, and sometimes an endless loop when the request itself causes a rebuild.
The chapter after the state-handling one examines this problem and its alternatives in depth.
What the snapshot keeps when the Future changes
When didUpdateWidget swaps in a new Future, the new snapshot is derived from the old one with only the connectionState changed. The previous data (or error) stays in place while the new request is waiting. This has two consequences:
- You can build "refresh in place" screens that show the old data under a thin progress indicator, by checking
connectionStateandhasDatatogether. - A builder that treats
hasDataas "finished loading" will show old data as if it were current during a refresh.
If you want a clean spinner on each reload, branch on connectionState == ConnectionState.waiting before looking at hasData.
Common mistakes
- Creating the
Futureinbuild. Covered above. This is the most frequent bug. - Using
hasDataas the loading test. It breaks fornullresults andFuture<void>. - Returning
nullfrom the builder. The builder must always return a widget. Returnconst SizedBox.shrink()for "nothing". - Expecting cancellation. Removing the widget does not stop the underlying work (HTTP call, database query). Only the callback is ignored.
- Wrapping the whole screen. A
FutureBuilderrebuilds only its own subtree, but if it sits at the top of a large screen, the whole screen rebuilds when the snapshot changes. Place it as close as possible to the widgets that depend on the result. - Doing heavy work in the builder. The builder runs on every rebuild, not only when the snapshot changes. Keep it light and free of side effects.
Exercises
Exercise
A FutureBuilder<void> wraps a save operation. The builder checks snapshot.hasData to decide whether to show "Saved". The screen shows a spinner forever even though the save succeeds. What is wrong, and what should the builder check instead?
Show answer
A Future<void> completes without a value, so snapshot.hasData is always false. The builder should check snapshot.connectionState == ConnectionState.done (after checking hasError) to know that the save finished.
Exercise
A screen calls setState once a second to update a clock. It contains FutureBuilder(future: api.loadProfile(), ...). Describe what happens on each tick, and give two ways to fix it.
Show answer
Each setState reruns build, which calls api.loadProfile() and passes a new Future object. didUpdateWidget sees a different future, drops the old subscription, subscribes to the new one, and the connection state returns to waiting. The result is a new request every second and a flickering UI. Fix it by creating the Future once, either by assigning it to a late final field in initState or by initializing a field with it, and passing that field to FutureBuilder. To reload deliberately, reassign the field inside setState.