Sub topic 3
The build method and BuildContext
Prerequisites: basic Dart classes, constructors, named parameters, null safety, and a working Flutter app. You should also know that Flutter UI is made from widgets arranged in a tree.
What the build method does
A widget's build method describes the part of the user interface that the widget controls. It receives a BuildContext and returns another widget.
BuildContext is an object that identifies a widget's location in the widget tree. It lets Flutter find information provided by widgets above the current widget, such as the app theme, screen size, localization, and navigation state.
The build method can run many times. Treat it as a description of the UI, not as a place for one-time work. Avoid starting network requests, creating controllers, or changing state directly inside it.
import 'package:flutter/material.dart';
void main() {
runApp(const GreetingApp());
}
class GreetingApp extends StatelessWidget {
const GreetingApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(colorSchemeSeed: Colors.indigo),
home: const GreetingPage(),
);
}
}
class GreetingPage extends StatelessWidget {
const GreetingPage({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(title: const Text('Greeting')),
body: Center(
child: Text(
'Hello, Flutter',
style: theme.textTheme.headlineMedium,
),
),
);
}
}Theme.of(context) searches upward from GreetingPage for the nearest theme. The page does not need to receive the theme as a constructor argument because MaterialApp provides it through the tree.
BuildContext and the widget tree
Consider this simplified tree:
Each widget has a context associated with its location. The context passed to build belongs to the widget being built. It can access ancestors, but it cannot access widgets that are below it.
This distinction matters when using inherited information:
final color = Theme.of(context).colorScheme.primary;
final width = MediaQuery.sizeOf(context).width;Theme.of and MediaQuery.sizeOf also arrange for the widget to rebuild when the relevant inherited value changes.
Build methods should stay focused
A useful build method usually follows this pattern:
- Read values from fields, parameters, or inherited widgets.
- Build and return the widget subtree.
- Leave lasting work to lifecycle methods or event callbacks.
For example, a button callback can update state, while build displays the current state. A StatefulWidget uses setState to tell Flutter that its next build should reflect changed data.
Do not save a context in a long-lived field. Instead, use the context supplied to the current build method or callback. If a state object needs to react when an inherited value changes, use didChangeDependencies.
Common context errors
| Situation | Safer approach |
|---|---|
| Using context after `await` | Check `mounted` before using it |
| Looking up a provider above the wrong context | Move the lookup below the provider |
| Doing one-time setup in `build` | Use `initState` or another lifecycle method |
| Creating a controller on every build | Create it once and dispose of it |
A common lookup error occurs when a widget tries to read a value from a provider that is created inside the same widget's returned subtree. The current widget's context is above that provider, so it cannot find it. Split the subtree into a child widget, then perform the lookup in that child.
Exercise
Why can Theme.of(context) work in a build method, but a controller should not be created there?
Show answer
The theme is tree information that the context can read during each build. A controller is a long-lived object that should be created once, reused, and disposed of when it is no longer needed.