الانتقال إلى المحتوى
تطبيقات الموبايلFlutter· 7 دقائق للقراءة

BuildContext Is a Place in the Tree: Why context Breaks After await

context is the element where your widget sits; after an await, that place may no longer exist.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Flutter 3.x
محتويات المقال

An edit-profile screen saves over the network, shows a "Profile saved" snackbar and closes itself. On slow connections, users tap back while the spinner is still turning. Seconds later, the error logs fill up with failures from the line right after the await. The code passed every manual test, because nobody testing it left the screen early.

The common misconception

The belief: 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.

It's an easy model to pick up. Nearly every Flutter API asks for a 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

The API docs define 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

An element leaves the tree when its route is popped, when its parent stops building it, when its key changes, or when a lazy list drops an item that scrolled away. Then 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.

What happens if you use it anyway depends on how you reach it. In a 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

The code after an 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".

Dart edit_profile.dart
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),        ),      );}

In a widget test that opened Home, then Settings, then this screen, tapped save and went back while the save was still running, the first version threw the "no longer has a context" error and showed no snackbar. The second showed "Profile saved" on the Settings screen, with no error, and left the user where they were. When the user stayed, it closed the screen as before.

The snackbar survives because MaterialApp builds its ScaffoldMessenger above every route, so the messenger outlives this screen. The pop is a different matter.

MythReality
context is a handle to the appIt's one element: the place where one widget sits
A context stays valid as long as you hold itOnly while mounted; once unmounted, never again
Navigator.of(context) finds "the" navigatorIt finds the nearest one above that place
Capturing the navigator before await fixes itIt silences the lint, and can close a screen the user already left
if (!mounted) return; is a hackIt's the documented check after an async gap

How to apply it in your project

  1. Make the lint impossible to ignoreKeep use_build_context_synchronously on, and raise it to an error in analysis_options.yaml under analyzer: errors: so an unguarded context can't reach a pull request.
  2. Ask "is this place still here?" after every awaitBefore touching context after an await, return early with if (!mounted) return;, or context.mounted for a context you received. Repeat it after each await, not just the first.
  3. Look up long-lived objects before the gap, on purposeA 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 mounted check.
  4. Cancel what you started in disposeThe 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 BuildContext is 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, check mounted (or context.mounted) before touching context.
  • Capture only objects meant to outlive the screen; never use a captured navigator to close a screen that may be gone.

📚 المصادر

  1. BuildContext class — Flutter API
  2. BuildContext.mounted — Flutter API
  3. State.context — Flutter API
  4. State.mounted — Flutter API
  5. use_build_context_synchronously — Dart linter rules

التعليقات (0)