Sub topic 9
Keeping auto-dispose providers alive in a test
This chapter assumes you can write Riverpod providers and notifiers, and that you know test, expect, and addTearDown. It also assumes you have seen ProviderContainer, container.read, and container.listen from earlier chapters. Here you will learn why an auto-dispose provider can lose its state in the middle of a test, and how to prevent it.
What auto-dispose does
A normal provider keeps its state for as long as its container exists. An auto-dispose provider keeps its state only while something is listening to it. When the last listener goes away, the container schedules the provider for disposal. The next read builds the provider from scratch, so build runs again and any state your code set is lost.
In an app this is the behavior you want. A screen opens, watches the provider, and closes. The state is freed when the screen goes away. In a test there is no screen. Calling container.read takes a snapshot of the value and does not register a lasting listener. Nothing holds the provider open.
The following diagram shows the lifecycle of an auto-dispose provider inside a container.
The timing detail that hides the bug
Disposal is scheduled, not immediate. The container waits until the current synchronous work finishes before it disposes anything. This has a practical consequence.
- A test that only does synchronous work, such as
read,increment,read, often passes without any listener, because the disposal never gets a chance to run. - A test that awaits something between two reads gives the container time to run the scheduled disposal. The second read then sees a freshly built provider.
This is why the bug is easy to introduce. A test passes, and later someone adds an await for an unrelated reason. The test starts failing, and the failure looks like the notifier lost its state for no reason.
Here is a test that shows the problem. It uses the Counter notifier from earlier chapters, registered as an auto-dispose provider.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class Counter extends Notifier<int> {
@override
int build() => 0;
void increment() => state++;
}
final autoCounterProvider =
NotifierProvider.autoDispose<Counter, int>(Counter.new);
void main() {
test('state is lost when nothing listens across an await', () async {
final container = ProviderContainer();
addTearDown(container.dispose);
container.read(autoCounterProvider.notifier).increment();
expect(container.read(autoCounterProvider), 1);
// Give the container time to run its scheduled disposal.
await Future<void>.delayed(Duration.zero);
// The provider was disposed, so build() ran again.
expect(container.read(autoCounterProvider), 0);
});
}This test passes, and that is the point. It documents the behavior you are protecting against. If you wrote the last line as expect(..., 1) you would get a failure that looks like a bug in your notifier.
The fix: hold a listener open
To keep an auto-dispose provider alive, give it a listener for the whole test. container.listen does this and returns a ProviderSubscription. As long as the subscription is open, the provider counts as being in use.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class Counter extends Notifier<int> {
@override
int build() => 0;
void increment() => state++;
}
final autoCounterProvider =
NotifierProvider.autoDispose<Counter, int>(Counter.new);
void main() {
test('state survives across an await while a listener is active', () async {
final container = ProviderContainer();
addTearDown(container.dispose);
final subscription = container.listen(autoCounterProvider, (_, __) {});
addTearDown(subscription.close);
container.read(autoCounterProvider.notifier).increment();
await Future<void>.delayed(Duration.zero);
expect(container.read(autoCounterProvider), 1);
});
}Three details matter here.
- The listener callback is
(_, __) {}. It does nothing. Its only job is to be registered. container.listenalso builds the provider if it has not been built yet, so you do not need a separate read to start it.- The
addTearDown(subscription.close)line is optional, because disposing the container closes all of its subscriptions. It is useful when you want the test to show clearly that the subscription is tied to the test's lifetime.
Reading through the subscription
A subscription has its own read() method. It returns the current value of the provider it holds open.
final subscription = container.listen(autoCounterProvider, (_, __) {});
container.read(autoCounterProvider.notifier).increment();
expect(subscription.read(), 1);This style makes it obvious which line is keeping the provider alive. Some teams prefer it for that reason. Using container.read is equally correct as long as the subscription is open.
Combining liveness and recording
You already know that container.listen can record every state change. The same listener can both keep the provider alive and collect the values. You do not need two listeners.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class Counter extends Notifier<int> {
@override
int build() => 0;
void increment() => state++;
}
final autoCounterProvider =
NotifierProvider.autoDispose<Counter, int>(Counter.new);
void main() {
test('one listener keeps the provider alive and records states', () async {
final container = ProviderContainer();
addTearDown(container.dispose);
final states = <int>[];
container.listen<int>(
autoCounterProvider,
(previous, next) => states.add(next),
);
container.read(autoCounterProvider.notifier).increment();
await Future<void>.delayed(Duration.zero);
container.read(autoCounterProvider.notifier).increment();
expect(states, [1, 2]);
});
}If you removed the listener here, the second increment would start from a rebuilt state of 0, and no states would be recorded at all.
Async auto-dispose providers
Async providers raise the same issue, and it is more likely to bite. A FutureProvider.autoDispose that has no listener can be disposed while the future is still running. In earlier chapters you read container.read(provider.future) and awaited it. That usually works for a simple case, but you should hold a listener when the test does more than one step, such as reading the provider, changing a fake, and reading again.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class FakeClock {
int calls = 0;
}
final clockProvider = Provider<FakeClock>((ref) => FakeClock());
final loadProvider = FutureProvider.autoDispose<int>((ref) async {
final clock = ref.watch(clockProvider);
clock.calls++;
await Future<void>.delayed(Duration.zero);
return clock.calls;
});
void main() {
test('a listener prevents a second load between awaits', () async {
final container = ProviderContainer();
addTearDown(container.dispose);
container.listen(loadProvider, (_, __) {});
final first = await container.read(loadProvider.future);
await Future<void>.delayed(Duration.zero);
final second = await container.read(loadProvider.future);
expect(first, 1);
expect(second, 1);
expect(container.read(clockProvider).calls, 1);
});
}The counter on FakeClock proves that the provider body ran once. Without the listener, the second read could rebuild the provider, and calls would reach 2. Counting how many times a body runs is a reliable way to check that a provider stayed alive.
Two alternatives, and when to use them
Holding a listener is the default for test code, because it does not change the provider you are testing. There are two other options.
| Approach | How | When to use it |
|---|---|---|
| Listener in the test | `container.listen(provider, (_, __) {})` | Default. Production code stays unchanged. |
| `ref.keepAlive()` in the provider | Call it inside the provider body | Only when the app itself needs the state to outlive its listeners. |
| Non-auto-dispose variant | Declare the provider without `.autoDispose` | When no part of the app needs disposal for that provider. |
Do not change a provider to non-auto-dispose just to make a test pass. That hides a testing problem by changing production behavior, and the app may then leak state it should have freed.
Testing that disposal happens
Sometimes disposal is the behavior you want to verify. For example, a provider may cancel a timer or close a stream in ref.onDispose. To test it, open a subscription, close it, and let the scheduled disposal run.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
final resourceProvider = Provider.autoDispose<String>((ref) {
ref.onDispose(() => disposed = true);
return 'open';
});
bool disposed = false;
void main() {
test('closing the last listener disposes the provider', () async {
disposed = false;
final container = ProviderContainer();
addTearDown(container.dispose);
final subscription = container.listen(resourceProvider, (_, __) {});
expect(subscription.read(), 'open');
expect(disposed, isFalse);
subscription.close();
await Future<void>.delayed(Duration.zero);
expect(disposed, isTrue);
});
}The await after close() is required. Disposal is scheduled, so checking disposed immediately would see false. The flag is a top-level variable here for brevity, and the test resets it first so the result does not depend on test order.
Common mistakes
- Reading once and assuming the state stays. A
container.readcall does not keep an auto-dispose provider alive. Add a listener before the first await. - Adding the listener after the first change. If you call
incrementbeforelisten, the provider may be built and then disposed before the listener exists. Open the listener first. - Expecting an immediate disposal. After
subscription.close(), wait a turn of the event loop before asserting that disposal ran. - Sharing a container. A container created at the top of the file and reused across tests carries listeners and state between tests. Create one container per test, as in earlier chapters.
- Fixing the test by editing the provider. Changing a provider's disposal behavior to satisfy a test changes the app. Fix the test first.
Exercises
Exercise
A test reads an auto-dispose counter provider, calls increment(), awaits Future<void>.delayed(Duration.zero), and then expects the value to be 1. It finds 0. Why does this happen, and what is the smallest change to the test that fixes it?
Show answer
With no listener, nothing keeps the auto-dispose provider alive. The await lets the container run its scheduled disposal, so the next read rebuilds the provider and build returns 0 again. The fix is to call container.listen(autoCounterProvider, (_, __) {}) before the first change, so a subscription holds the provider open for the rest of the test.
Exercise
You want to verify that a Provider.autoDispose runs its ref.onDispose callback once the last listener closes. Why must the test await after calling subscription.close(), and why should the test open a subscription at all instead of only calling container.read?
Show answer
Disposal is scheduled and runs after the current synchronous work, so asserting immediately after close() would see that the callback has not run yet. Awaiting a turn of the event loop, such as Future<void>.delayed(Duration.zero), lets it run. The test opens a subscription so the provider has a defined listener to remove. A plain read gives no listener whose removal you control, so you could not tell when disposal was triggered.