
BuildContext Is a Place in the Tree: Why context Breaks After await
- كاتب موثّق
- Flutter 3.x
محتويات المقال
await. The code passed every manual test, because nobody testing it left the screen early.
The common misconception
context is a handle to the app. You can pass it anywhere, keep it in a variable, use it after an await, and as long as the app is running, Navigator.of(context) will work.
context, so it feels like an ambient "app object" that's always around. Android developers have passed a Context around for years. And most of the time, you use it synchronously, inside build() or at the start of a tap handler, where it's always valid. The analyzer's complaint about async gaps shows up as an info-level hint, easy to read as style advice. The trouble only starts when time passes between getting the context and using it.
What actually happens
A context is an element: one place in the tree
BuildContext as "a handle to the location of a widget in the widget tree", and add that BuildContext objects are actually Element objects. Every widget gets its own. In a State, context is the element of your stateful widget, tied to that State for life: the docs call the association permanent, until dispose severs it.
Every .of(context) looks up from that place
Navigator.of, Theme.of, MediaQuery.of and ScaffoldMessenger.of walk up the ancestors of that element and return the nearest match. So the answer depends on where you ask: inside a nested navigator you get the nested one. Inside a build() method, context belongs to the widget being built, not to the widgets it returns, which is why Scaffold.of(context) can't find a Scaffold created in that same build(). A Builder placed inside the Scaffold gives you a context below it.
Places disappear
dispose runs, mounted turns false, and the docs are explicit: once unmounted, a context never becomes mounted again, and using it is only valid while mounted is true.
State, the context getter itself fails in debug mode with This widget has been unmounted, so the State no longer has a context (and should be considered defunct); with assertions off, as in a release build, it fails on a null check instead. A context passed in as a parameter fails on its first ancestor lookup: Looking up a deactivated widget's ancestor is unsafe.
await is where places disappear
await runs later, and in between, frames are drawn, taps are handled and routes are popped. That pause is an , and the use_build_context_synchronously lint, part of the flutter_lints set that new projects enable, flags any used across one: "Don't use 'BuildContext's across async gaps".
class _EditProfileState extends State<EditProfile> { String _name = ''; Future<void> _save() async { await widget.api.saveProfile(_name); // the user may leave meanwhile ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Profile saved')), ); Navigator.of(context).pop(); } @override Widget build(BuildContext context) => Scaffold( body: TextField(onChanged: (value) => _name = value), floatingActionButton: FloatingActionButton( onPressed: _save, child: const Icon(Icons.save), ), );}class _EditProfileState extends State<EditProfile> { String _name = ''; Future<void> _save() async { // Look up what outlives this screen before the gap final messenger = ScaffoldMessenger.of(context); await widget.api.saveProfile(_name); messenger.showSnackBar(const SnackBar(content: Text('Profile saved'))); if (!mounted) return; // the user already left: nothing to pop Navigator.of(context).pop(); } @override Widget build(BuildContext context) => Scaffold( body: TextField(onChanged: (value) => _name = value), floatingActionButton: FloatingActionButton( onPressed: _save, child: const Icon(Icons.save), ), );}MaterialApp builds its ScaffoldMessenger above every route, so the messenger outlives this screen. The pop is a different matter.
context is a handle to the app | |
Navigator.of(context) finds "the" navigator | |
await fixes it | |
if (!mounted) return; is a hack |
How to apply it in your project
Make the lint impossible to ignore Keep use_build_context_synchronouslyon, and raise it to an error inanalysis_options.yamlunderanalyzer: errors:so an unguarded context can't reach a pull request.Ask "is this place still here?" after every await Before touching contextafter anawait, return early withif (!mounted) return;, orcontext.mountedfor a context you received. Repeat it after eachawait, not just the first.Look up long-lived objects before the gap, on purpose A messenger or a repository that should act even after the screen closes can be looked up first. Anything tied to this screen, like closing it, waits for the mountedcheck.Cancel what you started in dispose The unmounted error itself suggests canceling active work in dispose. Cancel timers and subscriptions there, so fewer callbacks wake up to find their screen gone.
Key takeaways
A BuildContextis an element: one place in the tree, not a handle to the app.X.of(context)looks upward from that place and returns the nearest match.Once its widget leaves the tree, a context is unmounted for good, and using it fails. After every await, checkmounted(orcontext.mounted) before touchingcontext.Capture only objects meant to outlive the screen; never use a captured navigator to close a screen that may be gone.
التعليقات (0)