Sub topic 6
Provider lifetime: auto-dispose and keepAlive
This chapter assumes Dart async and await, Flutter widget basics, and basic Riverpod usage with ProviderScope, ConsumerWidget, and ref.watch.
A provider has a lifetime. Its lifetime determines how long Riverpod keeps its current value after widgets stop listening. With Riverpod code generation, providers are auto-disposed by default. This is usually the safest choice because unused state can be released automatically.
What auto-dispose does
An auto-dispose provider is disposed when it has no listeners. A listener is usually a widget that calls ref.watch. When the provider is disposed, Riverpod releases its current state and cancels work that belongs to that provider.
When a widget later watches the provider again, Riverpod creates a new provider instance and runs its body again.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'profile.g.dart';
@riverpod
Future<String> profile(Ref ref) async {
await Future<void>.delayed(const Duration(milliseconds: 300));
return 'Ada Lovelace';
}The generated provider is an auto-dispose provider. If a screen watches profileProvider, Riverpod keeps the result while that screen listens. When the screen leaves the widget tree and no other listener remains, Riverpod can discard the result.
Auto-dispose is useful for:
- Screen-specific data.
- Search results.
- Family providers with many parameter values.
- Temporary form or workflow state.
- Requests that should be refreshed when a screen is opened again.
Auto-dispose does not mean “dispose immediately after every read.” Riverpod keeps the provider while it has listeners. It also manages a short transition between listeners, so a provider is not needlessly recreated during every small widget-tree change.
Keeping a provider alive
Some state should remain available even when no widget currently watches it. Add keepAlive: true to the @Riverpod annotation:
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'settings.g.dart';
@Riverpod(keepAlive: true)
Future<Map<String, String>> settings(Ref ref) async {
return <String, String>{
'theme': 'dark',
'language': 'en',
};
}This provider stays alive until its ProviderContainer is disposed or the provider is explicitly invalidated. In a Flutter application, the container normally belongs to the ProviderScope near the root of the widget tree.
Use keepAlive for state that is application-wide or expensive to rebuild, such as:
- Authenticated session information.
- Configuration loaded once at startup.
- A shared repository cache.
- Data that should survive navigation between screens.
Keeping everything alive can waste memory and preserve stale data. Choose it because the state has a useful lifetime, not simply because rebuilding feels inconvenient.
Comparing the two lifetimes
| Choice | State with no listeners | Typical use |
|---|---|---|
| Default auto-dispose | Released and rebuilt later | Screen data and searches |
| `keepAlive: true` | Retained until invalidation or container disposal | App-wide configuration and caches |
The provider can still recompute when one of its dependencies changes. keepAlive prevents disposal caused by having no listeners; it does not freeze the provider forever.
This diagram shows the normal transition for an auto-dispose provider:
Lifetime and asynchronous work
When an auto-dispose provider performs asynchronous work, leaving the screen can make that work unnecessary. Riverpod disposes the provider's state, so later code should not assume that the original listener still exists.
For resources that need cleanup, register it with ref.onDispose:
import 'dart:async';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'polling.g.dart';
@riverpod
Stream<int> polling(Ref ref) {
final controller = StreamController<int>();
var value = 0;
final timer = Timer.periodic(const Duration(seconds: 1), (_) {
controller.add(value++);
});
ref.onDispose(() {
timer.cancel();
controller.close();
});
return controller.stream;
}The cleanup callback runs when the provider is disposed. This prevents timers, stream controllers, sockets, and similar resources from continuing after their provider is no longer needed.
Common lifetime mistakes
- Making every provider
keepAlivehides unnecessary rebuilds by spending more memory. - Expecting auto-disposed state to survive navigation leads to unexpected loading states.
- Forgetting
ref.onDisposecan leave timers or other external resources running. - Treating
keepAliveas permanent persistence is incorrect. Invalidating the provider or disposing its container still removes it. - A family with many arguments can create many cached instances. Auto-dispose helps release family instances that are no longer used.
Exercise
A provider loads data for one screen and owns a periodic timer. Should it use the default lifetime or keepAlive: true, and where should the timer be canceled?
Show answer
It should usually use the default auto-dispose lifetime. Register timer.cancel() with ref.onDispose so the timer stops when the provider is no longer watched.