Sub topic 6
Provider lifetime: auto-dispose and keepAlive
A provider's lifetime is the period between the moment its state is first created and the moment that state is thrown away. This chapter explains how Riverpod decides when to dispose of a provider generated with @riverpod. It also shows how to change that decision and which mistakes follow from getting it wrong.
It assumes you can already write @riverpod functions and classes, as shown in the earlier chapters, and that you know ref.watch inside a ConsumerWidget.
Auto-dispose is the default
Providers written by hand with Provider(...) keep their state for as long as the ProviderScope exists. Providers generated from @riverpod behave the other way around. They are auto-dispose by default. When nothing is listening to the provider any more, Riverpod destroys its state, and the next listener starts from scratch by running the provider's function or build method again.
A listener is any of these:
- a widget that calls
ref.watch(provider) - a call to
ref.listen(provider, ...) - another provider that watches it
- a
container.listen(provider, ...)subscription
A plain ref.read(provider) is not a listener. It reads the current value and leaves no subscription behind. This matters later in the pitfalls.
import 'dart:async';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'ticker.g.dart';
@riverpod
Stream<int> ticker(Ref 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;
}When the last widget watching tickerProvider leaves the screen, Riverpod disposes the provider and runs the callback registered with ref.onDispose. The timer stops and the controller closes. If the user returns, a new timer starts and the count begins at 0 again.
Auto-dispose is the safer default. Network responses, open streams, and timers do not pile up for screens the user has left. The cost is that state you expected to survive does not.
The lifecycle
Disposal does not happen at the exact moment the last listener is removed. Riverpod waits until the end of the current event-loop turn. If a new listener arrives in that window, which is common when one screen replaces another during a navigation transition, the state survives.
A provider can also be invalidated while it is still active. With ref.invalidate(provider), Riverpod disposes the current state, runs the onDispose callbacks, and rebuilds the provider if something still listens to it. Disposal by invalidation and disposal by lack of listeners share the same callbacks, so cleanup code belongs in ref.onDispose for both.
Keeping state alive with keepAlive
Some state should outlive any single screen. Examples are app settings, the logged-in user, or a repository holding an open database. To opt out of auto-dispose, use the @Riverpod annotation with keepAlive: true.
@Riverpod(keepAlive: true)
Future<Settings> settings(Ref ref) async {
return ref.watch(settingsRepositoryProvider).load();
}This provider loads once and keeps its value until the ProviderScope is removed, or until something calls ref.invalidate(settingsProvider).
The same option works on classes:
@Riverpod(keepAlive: true)
class Cart extends _$Cart {
@override
List<String> build() => const [];
void add(String sku) => state = [...state, sku];
void clear() => state = const [];
}A shopping cart is a typical case. If it were auto-dispose, leaving the cart screen would empty it.
The short @riverpod annotation and @Riverpod() with no arguments are equivalent. Both generate an auto-dispose provider.
| Annotation | Generated lifetime | Typical use |
|---|---|---|
| `@riverpod` | Auto-dispose | Screen-level data, search results, form state |
| `@Riverpod(keepAlive: true)` | Lives until scope is removed | Settings, session, repositories, caches |
| `@riverpod` plus `ref.keepAlive()` | Starts auto-dispose, becomes kept alive on demand | Cache only successful results |
Keeping alive conditionally with ref.keepAlive
Sometimes you want auto-dispose behavior in general, but you want to hold on to a result after an expensive step succeeds. Calling ref.keepAlive() inside the provider does that. It returns a KeepAliveLink. The provider stays alive until you call link.close(), after which normal auto-dispose rules apply again.
@riverpod
Future<List<Product>> featuredProducts(Ref ref) async {
final repository = ref.watch(productRepositoryProvider);
// If fetchFeatured throws, we never reach keepAlive,
// so a failed result is disposed like any other.
final products = await repository.fetchFeatured();
final link = ref.keepAlive();
final timer = Timer(const Duration(minutes: 5), link.close);
ref.onDispose(timer.cancel);
return products;
}Because keepAlive() is called after the await, an exception skips it. A failed request is therefore not cached, and the next listener retries. A successful result stays for five minutes even when no widget is watching. After the timer closes the link, the provider disposes as soon as it has no listeners.
This code assumes Product and productRepositoryProvider from your own app, and that dart:async is imported for Timer.
Lifetime and families
Each argument value of a family has its own state and its own lifetime. With an auto-dispose family, userProvider(1) and userProvider(2) are disposed independently. If one screen watches userProvider(1) and another stops watching userProvider(2), only the second is discarded.
The inverse is a trap. Annotating a family with keepAlive: true keeps every argument value ever requested.
@Riverpod(keepAlive: true)
Future<User> user(Ref ref, int id) async {
return ref.watch(userRepositoryProvider).fetchUser(id);
}If users browse thousands of profiles, this provider holds thousands of User objects until the app closes. Prefer the default auto-dispose behavior for families. If you do want caching, use ref.keepAlive() with a timer, as above, so entries expire.
How dependencies affect lifetime
When provider A watches provider B, A is a listener of B. That has two consequences.
First, a kept-alive provider keeps everything it watches alive. If settingsProvider is keepAlive: true and watches settingsRepositoryProvider, the repository provider stays alive too, even if it is auto-dispose.
Second, an auto-dispose provider cannot be kept alive by something that only reads it. A provider that uses ref.read(otherProvider) inside its body does not subscribe, so otherProvider may be disposed while the reader is still alive.
Choose lifetimes from the bottom up. If a provider with a long lifetime depends on providers that must also be long-lived, such as a database connection, mark those keepAlive explicitly. That keeps the intent visible in the code and does not depend on who happens to be watching.
Lifetime inside notifiers
Class-based providers follow the same rules. Their build method runs again after disposal, so any fields on the notifier instance are not safe places for data that must persist. Everything you want to keep belongs in state, and state is lost when the provider disposes.
@riverpod
class SearchQuery extends _$SearchQuery {
@override
String build() => '';
void update(String value) => state = value;
}If a user types a query, navigates away, and comes back, the query is empty again. That may be correct for a search box. For a filter the user expects to find unchanged, add keepAlive: true.
Async methods on a notifier can also finish after disposal. After an await in a method, the notifier may no longer be active, and assigning to state then throws. In Riverpod 3, check ref.mounted before assigning:
@riverpod
class Profile extends _$Profile {
@override
Future<User> build() => ref.watch(userRepositoryProvider).fetchUser(1);
Future<void> rename(String name) async {
final updated = await ref.read(userRepositoryProvider).rename(name);
if (!ref.mounted) return;
state = AsyncData(updated);
}
}In Riverpod 2, ref.mounted does not exist on the notifier's ref. Use a keepAlive provider if the work must complete, or track a flag you set in ref.onDispose.
Observing lifetime in tests
Auto-dispose also changes how tests behave. container.read(provider) creates the state, returns it, and leaves no listener. The state may be disposed before your next line runs. For a provider that needs to hold state between steps, add a subscription:
test('search query survives between reads', () {
final container = ProviderContainer();
addTearDown(container.dispose);
// The subscription counts as a listener and keeps the provider alive.
final subscription = container.listen(searchQueryProvider, (_, __) {});
addTearDown(subscription.close);
container.read(searchQueryProvider.notifier).update('flutter');
expect(container.read(searchQueryProvider), 'flutter');
});Without container.listen, a test that updates a notifier and then reads it can see the initial state. This usually happens when an await sits between the two calls. await container.read(userProvider(1).future) is safe because awaiting the future keeps the provider alive while it resolves.
Common mistakes
- State resets after navigation. The provider is auto-dispose and nothing listens to it while the screen is off. Add
keepAlive: trueor move the state to a provider that outlives the screens. - Using
ref.readinbuildfor something you need to react to.readcreates no subscription, so the provider neither rebuilds nor holds the dependency alive. Useref.watch. - Leaking resources. Timers, stream controllers, and sockets created in a provider must be closed in
ref.onDispose. Auto-dispose does not close them for you. - Everything marked
keepAlive. This hides the bug rather than fixing it. Memory use grows, and stale data is shown with no refresh. - Family with
keepAlive: true. As above, this caches every argument forever.
Summary of decisions
- Start with the default
@riverpod. It is the right choice for most providers. - Add
keepAlive: truefor state that must persist for the whole session. - Use
ref.keepAlive()withlink.close()when you want to cache a result for a limited time or only on success. - Close every resource you open in
ref.onDispose. - Check lifetime for families separately, because each argument value is its own instance.
Exercise
A @riverpod function Future<List<Message>> inbox(Ref ref) fetches the user's inbox. Users complain that every time they open a message and press Back, the inbox shows a loading spinner again. You want the list to stay in memory for two minutes after the last screen leaves, but you do not want a failed request to be cached. Which change do you make, and where does it go in the function?
Show answer
Keep the default auto-dispose provider and use ref.keepAlive() after the successful fetch. Do the await first, so an exception skips the rest. Then create the link, start a two-minute timer that closes it, and cancel the timer in ref.onDispose:
final messages = await ref.watch(messageRepositoryProvider).fetchInbox();
final link = ref.keepAlive();
final timer = Timer(const Duration(minutes: 2), link.close);
ref.onDispose(timer.cancel);
return messages;
Marking the provider keepAlive: true would cache failures and never expire.
Exercise
A test calls container.read(cartProvider.notifier).add('sku-1') on an auto-dispose Cart notifier, awaits some other work, then asserts that container.read(cartProvider) contains 'sku-1'. The assertion sometimes fails with an empty list. Why, and how do you fix the test?
Show answer
Nothing listens to cartProvider, so it is disposed at the end of an event-loop turn. The awaited work lets that happen, and the next read builds a fresh, empty state. Fix the test by keeping a listener open with final sub = container.listen(cartProvider, (_, __) {}); addTearDown(sub.close);, or by making the provider keepAlive: true if the cart really should persist in the app.