Sub topic 6
BuildContext is an Element
This chapter assumes you know how widgets and elements relate (the previous chapters) and have called Theme.of(context) or Navigator.of(context) without asking how it works. Here you will see what the context argument is and why that explains several common errors.
The object behind `context`
BuildContext is an abstract class. Its only concrete implementer in the framework is Element. When Flutter calls build(BuildContext context), the argument is the element that was created from your widget. A StatelessWidget receives its StatelessElement. A StatefulWidget's State.context returns its StatefulElement.
The framework hides the element behind an interface on purpose. It lets you ask questions about your position in the tree and blocks operations that would corrupt the tree, such as mounting or unmounting children. Don't cast context to Element.
Because a context is an element, it has three properties:
- It is a location. Two widgets that share a widget class have different contexts, because they sit at different places in the tree.
- It lasts as long as the element. The widget object is replaced on every rebuild. The element, and therefore the context, stays while
Widget.canUpdatereturns true. - It looks upward. Lookups start at your element and walk toward the root. A context cannot see what its own
buildmethod creates below it.
What you can ask a context
| Call | What it does |
|---|---|
| `context.widget` | Returns the widget this element currently holds. |
| `context.mounted` | Returns false after the element has been unmounted. |
| `context.findRenderObject()` | Returns the render object of this element, or of the nearest descendant that has one. |
| `context.size` | Returns the size of that render object, valid only after layout. |
| `context.dependOnInheritedWidgetOfExactType<T>()` | Finds the nearest ancestor `T` and registers this element as a dependent. |
| `context.getInheritedWidgetOfExactType<T>()` | Finds the same ancestor without registering a dependency. |
| `context.findAncestorStateOfType<T>()` | Walks up and returns the nearest `State` of type `T`. |
| `context.visitAncestorElements(visitor)` | Calls your function on each ancestor until it returns false. |
Helpers such as Theme.of(context), MediaQuery.of(context), and Directionality.of(context) are wrappers around these calls. Each one is a walk up the element tree from the context you pass in. The dependency registration is covered in the InheritedWidget chapter.
Same widget, different context
A widget's build method runs with the context of that widget's own element. Anything the method creates is a descendant of that element, so the method cannot look it up. This is the cause of the familiar error "Scaffold.of() called with a context that does not contain a Scaffold". The Material Scaffold can't be used in a short example, so the sketch below uses Directionality, which behaves the same way.
import 'package:flutter/widgets.dart';
void main() => runApp(const ContextDemo());
class ContextDemo extends StatelessWidget {
const ContextDemo({super.key});
@override
Widget build(BuildContext context) {
// This context belongs to ContextDemo's element, above the Directionality.
final above = Directionality.maybeOf(context);
return Directionality(
textDirection: TextDirection.ltr,
child: Builder(
builder: (innerContext) {
// Builder adds a new element below the Directionality.
final below = Directionality.maybeOf(innerContext);
return Text('outer: $above, inner: $below');
},
),
);
}
}The app prints outer: null, inner: TextDirection.ltr. Builder is a widget whose only job is to call a function with its own element as the context. The fix for a "context does not contain X" error is almost always to get a context that sits below X. You can do this with a Builder, or by extracting the part of the tree that needs the lookup into its own widget class.
Using a context after an `await`
A context is only meaningful while its element is in the tree. If the user leaves the screen during an await, the element is unmounted and the context becomes stale. Using it afterwards gives an error, or a lookup that reflects a position that no longer exists. Check mounted after every asynchronous gap.
import 'package:flutter/widgets.dart';
class DelayedLabel extends StatefulWidget {
const DelayedLabel({super.key});
@override
State<DelayedLabel> createState() => _DelayedLabelState();
}
class _DelayedLabelState extends State<DelayedLabel> {
String _text = 'loading';
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
await Future<void>.delayed(const Duration(seconds: 1));
if (!context.mounted) return; // the element may be gone by now
final direction = Directionality.of(context);
setState(() => _text = 'ready ($direction)');
}
@override
Widget build(BuildContext context) {
return Text(_text);
}
}Inside a State, mounted and context.mounted give the same answer. Wrap the widget in a Directionality, as in the first example, before running it.
Lookups during the wrong phase
Three timing rules follow from the element lifecycle:
initStatecannot register a dependency. The element is not fully attached yet, sodependOnInheritedWidgetOfExactType(and thereforeTheme.oforMediaQuery.of) asserts in debug builds. Do these lookups indidChangeDependencies, which the framework also calls again when the inherited widget changes.getInheritedWidgetOfExactTypeis allowed, but it won't notify you of changes.context.sizeis not ready duringbuild. Layout happens after the build phase of the same frame. In the first frame the render object does not have a size yet. Read the size in a callback fromWidgetsBinding.instance.addPostFrameCallback, or use aLayoutBuilderto react to constraints.- Ancestor walks are not free. Inherited lookups use a hash map on the element and are cheap.
findAncestorWidgetOfExactTypeandfindAncestorStateOfTypewalk the parent chain, so avoid calling them in a hotbuildmethod.
Exercise
A StatelessWidget builds a Directionality and, in the same build method, calls Directionality.of(context) using the method's own context. Why does this not find the Directionality it just created, and what are two ways to fix it?
Show answer
The context argument is the element of the widget whose build is running, and lookups only walk upward from that element. The new Directionality becomes a child of that element, so it is below the context and can't be found. Fix it by wrapping the code that needs the lookup in a Builder and using the builder's context, or by moving that code into its own widget class, whose element sits below the Directionality.
Exercise
In State.initState, you call Theme.of(context), which uses dependOnInheritedWidgetOfExactType. What goes wrong, and where should the call move?
Show answer
In debug builds the framework asserts, because a dependency can't be registered before initState has completed. Move the call to didChangeDependencies, which runs after initState and again whenever the inherited widget changes, or read the value inside build.