Sub topic 6
Do not create the Future inside build
This chapter explains why FutureBuilder restarts its request when you call an async function inside build, and how to prevent it. It assumes you know Dart async/await, StatefulWidget, setState, and initState/dispose. It also assumes you have read the earlier chapters on AsyncSnapshot and the basic FutureBuilder states.
The bug in one example
This code looks reasonable and often passes a quick manual test:
// 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...');
},
);
}_fetchName() is an ordinary function call. Dart evaluates it every time build runs, and each call returns a different Future object. FutureBuilder has no way to know that the two requests mean the same thing. It only compares object identity.
Why build runs more often than you expect
build is a pure description of the UI for the current state. Flutter may call it at any time, and you do not control when. Common triggers:
- A
setStatecall in this widget or in an ancestor that rebuilds this subtree. - A change in an
InheritedWidgetthe widget depends on, such asMediaQuery(the keyboard opens, the device rotates),Theme, orLocalizations. - An animation ticking in an ancestor.
- A hot reload during development.
- A route transition that changes inherited data.
A screen that rebuilds once or twice during normal use can still hide the bug. A text field with a focus change or an animated parent can expose it by rebuilding dozens of times per second.
What FutureBuilder does with a new Future
FutureBuilder is a StatefulWidget. Its State subscribes to the Future once and keeps the latest AsyncSnapshot. On every rebuild with a new configuration, Flutter calls its didUpdateWidget, which compares the old and new future properties:
- If
oldWidget.future != widget.future, the state stops listening to the old Future. The old Future is not cancelled. Dart Futures cannot be cancelled. The state only ignores its result. - It subscribes to the new Future.
- The snapshot moves to
ConnectionState.waiting.
Because != on Futures is identity comparison, a fresh Future from a function call is always "different".
The result is a loop of problems:
- Duplicate requests. Each rebuild triggers another network call, database query, or file read.
- Flicker. The
connectionStatereturns towaiting, so a spinner that depends on it reappears. Whether the previousdatais still visible depends on how your builder reads the snapshot. Do not rely on it. - Repeated side effects. If the function sends a
POSTor writes a row, it now does so repeatedly. - Possible infinite loop. If the builder's output causes a rebuild of the parent (for example it calls
setStateon completion), each completion triggers a new request, which triggers another completion.
The fix: create the Future once and store it in State
Create the Future in initState and keep it in a field. build then only reads the field, so every rebuild hands FutureBuilder the same object.
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.hasData) {
return Text('Hello, ${snapshot.data}');
}
return const CircularProgressIndicator();
},
);
}
}The widget must be a StatefulWidget. A StatelessWidget has nowhere to keep the Future between builds, because the widget object itself is recreated whenever its parent rebuilds.
Seeing the difference
This runnable demo counts how many times the loader runs. Press the button and watch the counter. Then switch the future: line to the stored version to compare.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(home: Scaffold(body: Center(child: CallCounterDemo()))),
);
class CallCounterDemo extends StatefulWidget {
const CallCounterDemo({super.key});
@override
State<CallCounterDemo> createState() => _CallCounterDemoState();
}
class _CallCounterDemoState extends State<CallCounterDemo> {
int _taps = 0;
int _calls = 0;
late final Future<String> _stored = _load();
Future<String> _load() async {
_calls++;
await Future<void>.delayed(const Duration(seconds: 1));
return 'Ada';
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
FutureBuilder<String>(
future: _load(), // try replacing with: _stored
builder: (context, snapshot) {
return Text('${snapshot.connectionState.name}, loads: $_calls');
},
),
ElevatedButton(
onPressed: () => setState(() => _taps++),
child: Text('Rebuild ($_taps)'),
),
],
);
}
}With _load() in build, every tap increments loads and the state goes back to waiting. With _stored, the count stays at 1 and the state stays done.
Other places to create the Future
initState is the most common choice, but it is not the only one. Pick based on what the Future depends on.
| Situation | Where to create the Future |
|---|---|
| No inputs, or inputs known at construction | `initState`, or a `late` field initializer |
| Depends on a constructor parameter that can change | `initState` plus `didUpdateWidget` |
| Depends on an `InheritedWidget` (`Theme.of`, `MediaQuery.of`, `Localizations.of`) | `didChangeDependencies`, with a guard |
| User action starts or restarts the request | An event handler that assigns inside `setState` |
| Shared across many screens | Outside the widget tree (a repository or state management layer) |
Parameters that change
If the widget receives an input such as a user ID, the Future must follow it. Store the Future, and replace it only when the input changes.
import 'package:flutter/material.dart';
class UserCard extends StatefulWidget {
const UserCard({super.key, required this.userId});
final int userId;
@override
State<UserCard> createState() => _UserCardState();
}
class _UserCardState extends State<UserCard> {
late Future<String> _user;
@override
void initState() {
super.initState();
_user = _fetchUser(widget.userId);
}
@override
void didUpdateWidget(UserCard oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.userId != widget.userId) {
_user = _fetchUser(widget.userId);
}
}
Future<String> _fetchUser(int id) async {
await Future<void>.delayed(const Duration(milliseconds: 500));
return 'User #$id';
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _user,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return Text(snapshot.data!);
},
);
}
}You do not need setState inside didUpdateWidget. Flutter calls build right after it, so the new field value is read in the same frame. The guard on userId matters: without it, every parent rebuild would restart the request, which is the original bug again.
Inherited dependencies
initState runs before the element is fully wired to its inherited widgets. Calling Theme.of(context) or MediaQuery.of(context) there fails, because dependency lookups that subscribe to changes are not allowed in initState. If the request needs such a value, create it in didChangeDependencies and guard it so it runs once:
Future<String>? _future;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_future ??= _load(Localizations.localeOf(context));
}didChangeDependencies can run again when the inherited value changes. Decide deliberately whether a locale change should reload. If it should, compare the old and new values instead of using ??=.
Subtle ways to get it wrong
- Helper methods that return a Future.
future: _repo.loadUser()is the same bug as_fetchName(). Any call that starts work belongs outsidebuild. - Getters.
Future<String> get _name => _fetchName();creates a new Future on every read. A getter used inbuildbehaves like a function call. - A lazy
latefield that is read only inbuild.late final Future<String> _name = _fetchName();is safe. The initializer runs once, on first access, and later reads return the same object. The request starts at the firstbuild, not atinitState, which is usually fine. - Creating the Future in the parent. If a
StatelessWidgetparent buildsFutureBuilder(future: fetch()), the parent's rebuilds cause the bug. The Future needs a stateful owner above the builder. - Keys that change. A
FutureBuilderunder a changingKeyis recreated as a new element, with a fresh state and a fresh subscription. Even a stored Future is then listened to again from the start. The request does not rerun, but the snapshot starts atwaitingfor one frame. - Already-completed Futures.
Future.value(1)still produces one frame inwaitingbefore the builder seesdone, because the result is delivered asynchronously. UseinitialDataif that single frame is visible.
Retrying relies on the same rule
Deliberately replacing the Future is how you refresh. In an event handler, assign a new Future inside setState. FutureBuilder sees a different object, subscribes to it, and shows the loading state again. The next chapter covers this in full. The key point here is that the new Future is created by a user action, not by build.
void _retry() {
setState(() {
_name = _fetchName();
});
}For this to compile, _name cannot be late final. Declare it as late Future<String> _name.
Checklist for reviewing your own code
- Search your
buildmethods forfuture:. The value should be a field, a parameter, or a variable, not a call with parentheses. - Confirm the owning widget is stateful, or that the Future lives outside the widget tree.
- If the Future depends on inputs, confirm something replaces it when they change, and nothing replaces it otherwise.
- Check that an unrelated
setState(for example, toggling a switch on the same screen) does not show a spinner again.
Exercise
A screen has a StatelessWidget that returns FutureBuilder(future: api.loadProfile(), ...). Its parent calls setState whenever the user types in a search box. Describe what the user sees and give two changes that fix it.
Show answer
Each keystroke rebuilds the parent, which rebuilds the child and calls api.loadProfile() again. This creates a new Future, so FutureBuilder unsubscribes from the old one, resubscribes, and returns to ConnectionState.waiting. The user sees the spinner reappear, or flicker, while typing, and the server receives a request per keystroke. Fixes: (1) convert the widget to a StatefulWidget, create the Future in initState (or a late field initializer), store it in a field, and pass the field to FutureBuilder; (2) move the loading into a layer above the widget, such as a repository or state management object that caches the result, and have the widget read from it. If the profile depends on a user ID, also add didUpdateWidget so the Future is replaced only when the ID changes.
Exercise
In _UserCardState, you remove the if (oldWidget.userId != widget.userId) check from didUpdateWidget and always assign _user = _fetchUser(widget.userId). What breaks, and why does it not break when the check is present?
Show answer
Without the check, every rebuild of the parent that creates a new UserCard configuration calls didUpdateWidget, even when userId is unchanged. That assigns a new Future each time, so FutureBuilder restarts the request and returns to waiting. This is the same bug as calling the function in build. With the check, a new Future is created only when the input actually differs, so unrelated rebuilds reuse the stored Future and keep the existing snapshot.
Exercise
Why can you not call MediaQuery.of(context) inside initState to build the Future, and where should that code go?
Show answer
initState runs before the element can register dependencies on inherited widgets, so a lookup that subscribes to an InheritedWidget such as MediaQuery.of is not allowed there and throws an error in debug mode. Put the code in didChangeDependencies, and guard it (for example with ??=, or by comparing the old and new inherited values) so the Future is not recreated on every dependency change unless you want that.