What is `BuildContext` in Flutter, and what is it used for?
Show answer — try answering out loud first
BuildContext is a reference to the location of a widget within the tree. It lets a widget find its ancestors (like the Theme, the Navigator, or a Provider) and perform operations that depend on where the widget sits in the tree. Every widget has its own BuildContext.
When Flutter calls build(BuildContext context), it gives you a context that represents "where I am" in the widget tree. With it you can:
- Look up inherited data above you:
Theme.of(context),MediaQuery.of(context),Navigator.of(context). - Access an ancestor
ProviderorInheritedWidget. - Navigate between screens.
Technically, the BuildContext is the Element associated with the widget. The key thing is to understand that it points to a position in the tree, not to the widget in the abstract.
import 'package:flutter/material.dart';
class Example extends StatelessWidget {
const Example({super.key});
@override
Widget build(BuildContext context) {
// I use context to read data from the tree's ancestors
final colors = Theme.of(context).colorScheme;
final width = MediaQuery.of(context).size.width;
return ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: colors.primary),
onPressed: () {
// The context is also used to navigate
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => const OtherScreen()),
);
},
child: Text("Width: $width"),
);
}
}
class OtherScreen extends StatelessWidget {
const OtherScreen({super.key});
@override
Widget build(BuildContext context) => const Scaffold();
}
Using a context that's no longer valid or that's in the wrong place in the tree. A classic case: saving the context and using it after an await when the widget has already been unmounted (the "don't use BuildContext across async gaps" error). Another: trying to use Scaffold.of(context) with the context of the widget that creates the Scaffold, when that context sits above the Scaffold and can't find it; the fix is usually a Builder to get a context lower down.
"
BuildContextrepresents a widget's position within the tree. I use it to access data coming from ancestors, likeTheme.of(context),MediaQuery.of(context), or aProvider, and to navigate withNavigator.of(context). Technically it's the widget'sElement. One important caution is not to use acontextafter anawaitif the widget might already have been unmounted, because thecontextwould no longer be valid."
Why do you sometimes need to wrap something in a Builder to get a different context?
See answer
Because .of(context) searches upward in the tree from that context. If the ancestor you're looking for (for example, the Scaffold) is created inside the same build, that method's context sits above it and can't find it. A Builder creates a new context lower in the tree, now below the Scaffold, so Scaffold.of(context) does locate it.