Sub topic 13
Provider lifecycle and autoDispose
This chapter assumes you can declare providers, read them with ref.watch and ref.read, and use family. Code targets flutter_riverpod 2.x.
What "lifecycle" means for a provider
A provider is a recipe, and the state it creates lives in a ProviderContainer. The ProviderScope at the root of your app owns that container. The container creates a provider's state the first time something reads or watches it. That state then stays in memory.
By default a provider is never disposed while its container is alive. This default is right for app-wide things like a repository, a settings object, or a logged-in user. It is wasteful for screen-specific data, such as the details of one product. With a plain family, every argument you ever used keeps its state until the app closes.
autoDispose changes the rule. The provider is disposed when nothing is listening to it. A listener is a widget that calls ref.watch or ref.listen, or another provider that watches it.
The lifecycle states
The diagram shows the path one provider state takes.
Two points matter in practice:
- Disposal does not happen at the exact moment the last listener leaves. Riverpod waits briefly, so a widget that is removed and re-added in the same frame does not lose its state.
- A provider can also be disposed while it still has listeners.
ref.invalidateand a change in a watched dependency both throw the old state away and rebuild it.
Making a provider auto-disposing
Add .autoDispose to the provider type. It combines with family, as in the earlier chapter.
final userNameProvider =
FutureProvider.autoDispose.family<String, int>((ref, id) async {
await Future<void>.delayed(const Duration(milliseconds: 200));
return 'User $id';
});Open a page that watches userNameProvider(42) and the fetch runs. Leave the page and the state for 42 is released. Open it again and the fetch runs again.
For a Notifier, the 2.x API has a matching pair of classes:
class DraftNotifier extends AutoDisposeNotifier<String> {
@override
String build() => '';
void update(String text) => state = text;
}
final draftProvider =
NotifierProvider.autoDispose<DraftNotifier, String>(DraftNotifier.new);Here the draft text is cleared when the editing screen closes, which is usually what you want for a form.
Cleaning up with ref.onDispose
If a provider owns something that must be closed, such as a timer, a stream controller, or a socket, register the cleanup with ref.onDispose.
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final tickerProvider = StreamProvider.autoDispose<int>((ref) {
final controller = StreamController<int>();
var count = 0;
final timer = Timer.periodic(
const Duration(seconds: 1),
(_) => controller.add(count++),
);
ref.onDispose(() {
timer.cancel();
controller.close();
});
return controller.stream;
});onDispose callbacks run every time the state is destroyed, not only when the provider leaves the app. That includes a rebuild caused by ref.watch seeing a new value. Each rebuild therefore starts from a clean slate, and the cleanup must be safe to run many times.
Riverpod also offers ref.onCancel and ref.onResume. They fire when the last listener leaves and when a new one arrives, before disposal happens.
Keeping state alive on purpose
Sometimes you want auto-disposal in general but a cache for a while. ref.keepAlive() returns a link that blocks disposal until you call close().
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final cachedUserProvider =
FutureProvider.autoDispose.family<String, int>((ref, id) async {
await Future<void>.delayed(const Duration(milliseconds: 200));
final name = 'User $id';
// Success only: keep the result for 30 seconds after the last listener leaves.
final link = ref.keepAlive();
final timer = Timer(const Duration(seconds: 30), link.close);
ref.onDispose(timer.cancel);
return name;
});Because keepAlive is called after the await, a failed request never reaches it. The error state is disposed as usual, and the next visit retries. Calling keepAlive at the top of the function would cache errors too.
Choosing between the two modes
| Situation | Use | Reason |
|---|---|---|
| Repository, API client, settings | Plain provider | Needed for the whole app, cheap to hold |
| Data for one screen or one item | `autoDispose` | Frees memory and refetches fresh data on return |
| Per-item data, many ids | `autoDispose.family` | Stops one entry per id piling up |
| Form draft | `autoDispose` Notifier | Resets when the form closes |
| Expensive result worth caching briefly | `autoDispose` plus `keepAlive` | Fresh enough, not refetched on every visit |
Common mistakes
- Reading an auto-dispose provider only with
ref.read. Nothing is listening, so the state can be disposed before you use it again. A counter incremented in a button callback, with no widget watching it, resets to zero. - Testing with
container.readalone. In a test, nothing keeps the state alive between calls. Hold a subscription withcontainer.listenfor as long as the test needs the value. - Using
refafter disposal. An async callback that finishes after the provider is gone can throw. Check cancellation or tie the work toref.onDispose. - Forgetting cleanup. A timer that survives disposal keeps firing into a closed controller. Always pair resource creation with
ref.onDispose. - Making everything
autoDispose. An auto-disposing repository is rebuilt over and over. Dispose per-screen state, not shared services.
Testing the lifecycle
This test holds a subscription, so the state survives between reads. It defines its own provider so it can run alone.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
final nameProvider =
FutureProvider.autoDispose.family<String, int>((ref, id) async {
return 'User $id';
});
void main() {
test('state is kept while a listener exists', () async {
final container = ProviderContainer();
addTearDown(container.dispose);
final sub = container.listen(nameProvider(1), (previous, next) {});
expect(await container.read(nameProvider(1).future), 'User 1');
sub.close();
});
}Exercise
A screen has a button whose handler runs ref.read(draftProvider.notifier).update('hi'). draftProvider is an auto-disposing Notifier provider, and no widget watches it yet. Later a second screen watches it and shows an empty string. Why, and what is the smallest fix?
Show answer
Nothing was listening when update ran, so the state was disposed shortly afterwards. The second screen created a fresh state with build() returning ''. The smallest fix is to have a widget that outlives both screens watch the provider. Alternatively, make draftProvider non-auto-disposing, or call ref.keepAlive() inside it, if the draft really must persist.
Exercise
Why does cachedUserProvider call ref.keepAlive() after the await and not at the top of the function?
Show answer
If the request throws, the code after the await never runs, so the error result is not kept alive. The provider is disposed once its listeners leave, and the next visit retries the request. Calling keepAlive first would cache failures for 30 seconds.