Sub topic 3
The build method and BuildContext
What this chapter assumes
You should know basic Dart classes and constructors, and how to run a small Flutter app. You should also have read the earlier chapters on the widget tree and on what a widget is. This chapter covers what build is allowed to do, when Flutter calls it, and what the BuildContext argument represents.
What build does
Every StatelessWidget and every State class has a build method. It takes a BuildContext and returns a Widget:
Widget build(BuildContext context)The returned widget is a description of part of the UI, based on the widget's current configuration and state. Flutter compares that description with the previous one and updates only what changed. build does not draw anything and does not touch the screen.
You never call build yourself. The framework calls it, and it can do so at any time, as often as every frame during an animation. This gives one rule that most other advice follows from: build must be fast and free of side effects.
When the framework calls build
A widget's build runs again in these cases:
- The widget is first inserted into the tree.
- Its parent rebuilds and passes it a new configuration. A
constwidget instance that is identical to the old one is skipped. - For a
State,setStateis called. - An
InheritedWidgetit depends on changes, such asTheme,MediaQuery, or aDirectionality. - The app is hot reloaded.
Because of this, you cannot assume build runs once per widget, or only when you expect it to. Write it as if it could run on every frame.
What BuildContext is
BuildContext is a handle to the location of a widget in the tree. Widgets are cheap, short-lived configuration objects, so a widget cannot know where it sits. The framework tracks that through an Element, one for each widget instance that is mounted in the tree. Element implements BuildContext, so the context you receive is the element for the widget whose build is running.
The context lets you ask questions about the tree above you:
final theme = Theme.of(context);
final size = MediaQuery.sizeOf(context);
final navigator = Navigator.of(context);Each of method starts at your context and walks up the ancestors until it finds the widget it is looking for. Theme.of(context) finds the nearest Theme above you. If there is none, it falls back to the app's default theme. Others, such as Navigator.of, throw an error when no matching ancestor exists.
A context belongs to one place in the tree. It is not a global handle, and you should not store it in a field or pass it around for later use. Section "Using context after an async gap" shows what goes wrong when you do.
The common error: using the wrong context
Lookups go up from the context you pass, starting at that widget's own position. A widget that you create inside build is below your context, so a lookup with your context cannot see it.
This example tries to read a theme it has just created:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: ThemedBox())));
class ThemedBox extends StatelessWidget {
const ThemedBox({super.key});
@override
Widget build(BuildContext context) {
return Theme(
data: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
),
child: Container(
width: 100,
height: 100,
// Wrong: this context is ThemedBox's own, which is above the Theme.
// It returns the app's theme, not the green one.
color: Theme.of(context).colorScheme.primary,
),
);
}
}The box does not turn green, because context is the position of ThemedBox, and the Theme is a descendant. The fix is to run a second build that sits below the Theme. A Builder widget does this. It calls your function with its own, deeper context:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: ThemedBox())));
class ThemedBox extends StatelessWidget {
const ThemedBox({super.key});
@override
Widget build(BuildContext context) {
return Theme(
data: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
),
child: Builder(
builder: (innerContext) => Container(
width: 100,
height: 100,
color: Theme.of(innerContext).colorScheme.primary,
),
),
);
}
}You can also move the inner part into its own widget class, which is usually clearer. The same mistake appears with Scaffold.of, Navigator.of, and any custom InheritedWidget that you provide and read inside one build method.
Keep build pure
A pure build returns the same widgets for the same inputs and changes nothing outside itself. Things that do not belong in build:
- Network or database calls.
- Calling
setState. This schedules another build while one is running and causes errors or loops. - Creating objects that hold resources, such as
TextEditingController,AnimationController, or stream subscriptions. They would be recreated on every rebuild, and the old ones would leak. - Mutating fields or lists that other code reads.
- Expensive computation that you could do once or cache.
Compare these two versions of a text field:
import 'package:flutter/material.dart';
// Wrong: a new controller on every build. Typed text is lost
// whenever the parent rebuilds, and old controllers are never disposed.
class BadField extends StatelessWidget {
const BadField({super.key});
@override
Widget build(BuildContext context) {
final controller = TextEditingController();
return TextField(controller: controller);
}
}
// Right: the State creates the controller once and disposes it.
class GoodField extends StatefulWidget {
const GoodField({super.key});
@override
State<GoodField> createState() => _GoodFieldState();
}
class _GoodFieldState extends State<GoodField> {
final TextEditingController _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextField(controller: _controller);
}
}Work that should happen once belongs in initState, and work that responds to user input belongs in event handlers such as onPressed. Code inside a handler is not part of build, so it can call setState, start requests, and navigate.
Reading dependencies and rebuilds
Most of methods do more than find a widget. They register your context as a dependent of that InheritedWidget. When the inherited widget changes, the framework rebuilds every dependent. Calling Theme.of(context) therefore means "rebuild me when the theme changes."
This is the reason to prefer narrow lookups. MediaQuery.of(context) depends on all media data, so your widget rebuilds when the keyboard opens or the orientation changes. MediaQuery.sizeOf(context) depends only on the size, so it rebuilds less often.
Outside build, you often want to read a value without subscribing. The usual case is an event handler. Inside initState you cannot subscribe at all, because the element is not yet fully part of the tree. Dependencies are read in didChangeDependencies or in build:
| Where you are | What you want | What to use |
|---|---|---|
| `build` | Read a value and rebuild when it changes | `Theme.of(context)`, `MediaQuery.sizeOf(context)` |
| `didChangeDependencies` | React to a dependency change once | The same `of` methods |
| `initState` | Read an inherited value | Avoid. Move the code to `didChangeDependencies` |
| Event handler | Act on the tree, such as navigating | `Navigator.of(context)` |
Using context after an async gap
A BuildContext stays valid only while its element is mounted. If you await something and the widget is removed in the meantime (the user navigates back, for example), the context points to a dead element. Using it can throw errors or act on the wrong place.
Check that the widget is still mounted after any await before you use the context:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: SaveButton())));
class SaveButton extends StatefulWidget {
const SaveButton({super.key});
@override
State<SaveButton> createState() => _SaveButtonState();
}
class _SaveButtonState extends State<SaveButton> {
Future<void> _save() async {
await Future<void>.delayed(const Duration(seconds: 1));
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Saved')),
);
}
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(onPressed: _save, child: const Text('Save')),
);
}
}Inside a State, the mounted property answers the question. In a stateless widget, or in a function that only receives a context, use context.mounted. The Dart analyzer has a lint, use_build_context_synchronously, that flags a context used after an await without such a check.
Helper methods versus widget classes
A long build method is hard to read, and it tempts you to split it. There are two ways:
- A helper method such as
Widget _buildHeader()in the same class. - A separate widget class such as
class Header extends StatelessWidget.
A helper method still runs inside the parent's build. Everything it returns is rebuilt whenever the parent rebuilds. A separate widget has its own element and its own build, and Flutter can skip it when it is created with const and its inputs are unchanged. A class also gets its own context, which is handy when you need a lookup below a provider. Use helper methods for small readability splits, and separate classes when the part is reusable, has its own state, or is expensive to rebuild.
Exercise
A widget's build method returns Scaffold(body: Builder(builder: (c) => Text('${Theme.of(context).brightness}'))) and wraps it in a Theme created in the same build. The text always shows the app's brightness, not the new theme's. Why, and what single change fixes it?
Show answer
The Theme.of(context) call uses the outer context of the widget whose build is running. That context sits above the new Theme, so the lookup never sees it. The Builder provides a deeper context, c, but the code ignores it. Passing c to Theme.of(c) fixes it. This only works if the Theme wraps the Builder.
Exercise
A State method does await fetchUser(); and then calls Navigator.of(context).pop();. What can go wrong, and how do you guard against it?
Show answer
The user may have left the screen during the await, so the State is unmounted and the context is no longer valid. Add if (!mounted) return; after the await and before using context.