Riverpod throws a StateError when ref is used after the widget is gone
Using "ref" when a widget is about to or has been unmounted is unsafe.Short answer
Riverpod's ref in a widget is tied to its BuildContext. Once the widget is deactivated or unmounted, any ref.read, ref.watch or ref.listen throws a StateError. It happens when a callback resumes after an await, or when dispose() reads a provider. Check context.mounted before using ref after an await, and copy what dispose() needs into a field earlier.
Fix it fast
1Find out which cause you have
Read the stack trace and find the line in your own code that touched ref. Then see whether it sits after an await or inside dispose(). That tells you which cause below applies.
# In the terminal that runs the app, look for the first frame from your package: flutter run -v 2>&1 | grep -n "package:my_app/"2Match what you see, then jump to its fix
- 1
The trace points at a line below an await in a button handler or an initState/async method, and the error only appears when you navigate away quicklyref is used after an await, once the user has left the screenFix - 2
The trace contains State.dispose or _ConsumerState.dispose, and the message mentions saving provider state in a fielddispose() reads a provider through refFix - 3
You added one mounted check, but the error moved to a later line in the same methodThe mounted check is missing after the last await of a longer chainFix
- 1
What does the error look like?
Using "ref" when a widget is about to or has been unmounted is unsafe.Ref relies on BuildContext, and BuildContext is unsafe to use when the widget is deactivated.To safely refer to the state of providers inside State.dispose(), save the provider state in a field of your State class.
Cause 1 of 3
ref is used after an await, once the user has left the screen
1Check
Find every await in the method and see whether ref.read, ref.watch or ref.invalidate runs after it. The throw happens when the widget's context is no longer mounted, which is exactly what the awaited work allows.
grep -n -A4 "await" lib/features/profile/profile_page.dart2Fix
Stop right after the await if the widget is gone. In a ConsumerStatefulWidget the State's context is the one to test, so use the mounted property. If the code lives in a function that received a BuildContext, test context.mounted.
Future<void> _save() async {
await ref.read(profileRepositoryProvider).save(_draft);
if (!mounted) return; // State: use mounted
ref.invalidate(profileProvider);
}3Verify
Tap save and leave the screen before the request ends. The StateError no longer appears.
flutter runConfirmed by raw.githubusercontent.com
Cause 2 of 3
dispose() reads a provider through ref
1Check
Search dispose() for ref.read or ref.watch. By the time dispose runs the widget is already deactivated, so the call is refused.
grep -n -B2 -A8 "void dispose" lib/features/profile/profile_page.dart2Fix
Take what you need while the widget is still alive (initState or didChangeDependencies) and keep it in a field. dispose() then uses the field, not ref.
late final ProfileController _controller;
@override
void initState() {
super.initState();
_controller = ref.read(profileControllerProvider.notifier);
}
@override
void dispose() {
_controller.flushDraft(); // no ref here
super.dispose();
}3Verify
Pop the screen. dispose() finishes without the StateError.
flutter runConfirmed by raw.githubusercontent.com
Cause 3 of 3
The mounted check is missing after the last await of a longer chain
1Check
Each await is a new gap. A check placed before the first await does not cover the code after the second one.
dart analyze2Fix
Add the check after every await that is followed by context or ref use. The lint use_build_context_synchronously reports the spots for BuildContext.
await first();
if (!mounted) return;
await second();
if (!mounted) return;
ref.invalidate(profileProvider);3Verify
dart analyze reports no use_build_context_synchronously warnings in the file.
dart analyze lib/features/profile/profile_page.dartConfirmed by dart.dev
How do I stop it coming back?
- After every await in a widget method, check mounted (State) or context.mounted before touching ref or context.
- Keep dispose() free of ref calls. Save the notifier or value in a field in initState.
- Turn on the use_build_context_synchronously lint so the analyzer shows missing checks.
- Move long work into a provider or notifier method, so the widget only starts it.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- Qist BazaarA buy-now-pay-later marketplace built from a blank repo, now past 100K downloads on Google Play.
- SessionBirdAn omnichannel engagement suite in Flutter: campaigns, chatbot, tickets, analytics and live calling.
Related fixes
Mobile apps
AudioCache has no play method after updating audioplayers
The method 'play' isn't defined for the type 'AudioCache'.
Since audioplayers 1.0, AudioCache only turns asset files into local files and caches them.
2 causes, each with a fixMobile apps
Flutter Bloc throws that emit was called after the event handler completed
emit was called after an event handler completed normally.
Each on<Event> handler gets its own Emitter, and it stops working the moment the handler's returned Future completes.
2 causes, each with a fixMobile apps
analysis_options.yaml: the URI it includes can't be found
include_file_not_found
The analyzer reports include_file_not_found when the file named after include: in analysis_options.yaml does not resolve.
2 causes, each with a fixMobile apps
Dart error: the body might complete normally and return null for a non-nullable type
body_might_complete_normally
Dart found a path through your function or callback that reaches the closing brace without a return.
3 causes, each with a fixMobile apps
Dart throws ConcurrentModificationError while looping over a list
ConcurrentModificationError
Dart throws this when a collection changes size while something iterates it.
2 causes, each with a fixMobile apps
Dart cannot turn a compact timestamp like 20201101153000 into a DateTime
FormatException: Invalid date format
DateTime.parse accepts a subset of ISO 8601, and a time part must be introduced by T or a space.
2 causes, each with a fix