flutter
lifecycle_error
ai_generated
true
Looking up a deactivated widget's ancestor is unsafe.
ID: flutter/build-context-deactivated
85%Fix Rate
89%Confidence
3Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3 | active | — | — | — |
Root Cause
BuildContext used after the widget has been removed from the tree. Commonly occurs when navigating or showing dialogs from async callbacks.
genericWorkarounds
-
92% success Check mounted before using context after an await
await someAsyncOp(); if (!mounted) return; Navigator.of(context).push(...);
Sources: https://api.flutter.dev/
-
88% success Use a NavigatorKey or router at the app level for navigation from async code
final navigatorKey = GlobalKey<NavigatorState>(); // set on MaterialApp, use navigatorKey.currentState!.push(...)
-
85% success Move async logic to a provider/bloc and react to state changes in the widget
Widget listens to state stream and navigates in build/listener, not in async callback
Dead Ends
Common approaches that don't work:
-
Store BuildContext in a variable and use it later in async code
82% fail
Context becomes invalid after the widget is deactivated; storing it does not keep it alive
-
Use a GlobalKey to get context from anywhere
70% fail
GlobalKey.currentContext can also be null after widget disposal; same lifecycle issue