Sub topic 6
Do not create the Future inside build
This chapter assumes you know Dart async, await, and Future, plus Flutter StatefulWidget, build, initState, dispose, and setState.
A Future represents one value that will be available later. FutureBuilder listens to that future and rebuilds its child when the future changes state. The important detail is that Flutter may call build many times. A rebuild does not mean that your asynchronous request should start again.
Why `build` can run repeatedly
Flutter calls build when the widget is first displayed and whenever relevant state changes. Common causes include:
- Calling
setState. - A parent widget rebuilding.
- A dependency such as an inherited theme changing.
- An animation or stream updating nearby UI.
The build method should describe the current UI from current state. It should avoid starting work with side effects, such as network requests, database reads, or file operations.
This pattern creates a new Future whenever build runs:
class UserGreeting extends StatelessWidget {
const UserGreeting({super.key});
Future<String> _fetchName() async {
await Future<void>.delayed(const Duration(seconds: 1));
return 'Ada';
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _fetchName(),
builder: (context, snapshot) {
return Text(snapshot.data ?? 'Loading...');
},
);
}
}_fetchName() runs again for every rebuild. FutureBuilder receives a different future, so it subscribes to that new future. The snapshot can return to waiting, and the request may repeat.
Store the Future in State
Create the future outside build, usually in initState, and store it in a field. Then every rebuild passes the same future to FutureBuilder.
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.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return Text('Hello, ${snapshot.data}');
},
);
}
}The late final field is assigned once. The future starts when initState runs, not each time the widget builds. FutureBuilder can rebuild many times while still observing the same asynchronous operation.
A field initializer can also work:
late Future<String> _name = _fetchName();Use initState when the setup needs several statements or depends on lifecycle ordering. If the request depends on a widget property, initialize it in initState and compare the old and new property in didUpdateWidget.
Refreshing deliberately
A stable future should not mean that data can never refresh. Refreshing is a state change that intentionally replaces the old future:
late Future<String> _name = _fetchName();
void _refresh() {
setState(() {
_name = _fetchName();
});
}Assigning the new future inside setState tells FutureBuilder to subscribe to it. The UI can show loading again while the replacement request runs. Do not call _refresh from build; connect it to a button, pull-to-refresh action, or another deliberate event.
A practical rule
Ask whether the future represents new work or the same work being displayed.
- Same work: store the future in
Stateand pass the stored value toFutureBuilder. - New work: create a replacement future in an event handler or lifecycle method, usually inside
setState. - Changing input: update the future in
didUpdateWidgetwhen the relevant input changes.
Exercise
Why can calling _loadItems() directly in FutureBuilder.future cause repeated requests, and where should you create the future instead?
Show answer
Each build can call _loadItems() and create a new Future. Create it in initState, store it in State, and replace it only when a deliberate refresh or input change requires new work.