Sub topic 2
One container per test, disposed with addTearDown
This chapter assumes you know Dart and flutter_test, can write a basic test with expect, and have used Provider, NotifierProvider, and ref.watch versus ref.read in Riverpod. Examples use Riverpod 2.x APIs (Notifier, NotifierProvider). The container lifecycle works the same way in later versions.
Where provider state lives
A provider declared at the top level of a file, such as final counterProvider = ..., does not hold any state itself. It is a recipe: a description of how to create a value. The state is created and stored in a ProviderContainer. In a running Flutter app, ProviderScope creates one container for you. In a plain Dart test, you create it yourself.
That split is the reason tests can be isolated. Two containers that use the same counterProvider each have their own counter. The test rule follows from this:
- Create a new container for every test.
- Dispose of it when the test ends, whether the test passed or failed.
The first rule keeps state from leaking between tests. The second releases everything the providers acquired.
The basic pattern
Here is the pattern used throughout this tutorial.
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 counterProvider = NotifierProvider<Counter, int>(Counter.new);
void main() {
test('increment updates state', () {
final container = ProviderContainer();
addTearDown(container.dispose);
expect(container.read(counterProvider), 0);
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
});
}Two lines matter here. ProviderContainer() creates a fresh, empty container. addTearDown(container.dispose) registers the dispose method to run after this test finishes. Note that you pass container.dispose without calling it. You are handing the test framework a function to call later.
Why addTearDown instead of a trailing dispose call
You could write container.dispose(); as the last line of the test. That fails in one important case: if an expect fails or any line throws, execution never reaches the last line. The container stays alive, and any resources it holds (timers, streams, open listeners) stay alive with it.
addTearDown callbacks run when the test ends, regardless of outcome. Registering the callback on the line right after creating the container also protects you from later edits. If someone adds code between creation and the end of the test, disposal is still guaranteed.
// Fragile: skipped if an expect above it fails.
test('fragile', () {
final container = ProviderContainer();
expect(container.read(counterProvider), 0);
container.dispose();
});
// Reliable: registered immediately, runs however the test ends.
test('reliable', () {
final container = ProviderContainer();
addTearDown(container.dispose);
expect(container.read(counterProvider), 0);
});What dispose does
Calling dispose on a container tears down every provider the container created. For each provider that was initialized, Riverpod runs the callbacks registered with ref.onDispose, then discards the state. Providers that were never read were never created, so there is nothing to clean up for them.
The next test makes this visible.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('disposing the container runs onDispose callbacks', () {
var disposed = false;
final resourceProvider = Provider<int>((ref) {
ref.onDispose(() => disposed = true);
return 42;
});
final container = ProviderContainer();
expect(container.read(resourceProvider), 42);
expect(disposed, isFalse);
container.dispose();
expect(disposed, isTrue);
});
}This test calls dispose directly because the disposal itself is what it checks. In ordinary tests, use addTearDown.
This is also why disposal matters beyond tidiness. Real providers often close a StreamController, cancel a Timer, or release a database handle in onDispose. A test that skips disposal leaves those running. Leaked timers can fire during a later test and cause failures that look unrelated to their cause.
After a container is disposed, you should not use it again. In debug mode, which is how tests run, reading from a disposed container throws a StateError. Treat dispose as the end of that container's life.
The test lifecycle
The diagram shows what happens around a single test when you use this pattern.
What goes wrong with a shared container
A tempting shortcut is to create one container at the top of the file and reuse it. It works until a second test depends on state the first one changed.
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 counterProvider = NotifierProvider<Counter, int>(Counter.new);
// Shared across every test in the file: avoid this.
final sharedContainer = ProviderContainer();
void main() {
test('first increment', () {
sharedContainer.read(counterProvider.notifier).increment();
expect(sharedContainer.read(counterProvider), 1);
});
test('starts at zero', () {
// Fails if the test above ran first: the value is already 1.
expect(sharedContainer.read(counterProvider), 0);
});
}The second test passes if it runs alone and fails if the whole file runs in order. That kind of order dependence is expensive to debug, because the failing test has no bug of its own. The cause lives in a test that ran earlier.
The shared container is also never disposed, so provider resources live until the process exits.
Sharing setup with setUp
If every test in a group needs a container, you can create it in setUp. setUp runs before each test, so every test still gets a new container.
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 counterProvider = NotifierProvider<Counter, int>(Counter.new);
void main() {
group('Counter', () {
late ProviderContainer container;
setUp(() {
container = ProviderContainer();
addTearDown(container.dispose);
});
test('starts at zero', () {
expect(container.read(counterProvider), 0);
});
test('increments', () {
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
});
});
}Calling addTearDown inside setUp is allowed. The callback is attached to the test that is about to run, so each test disposes its own container. Declare the variable as late ProviderContainer container rather than late final. A final variable can be assigned only once, and setUp assigns it again for every test.
Compare the options:
| Approach | New state per test | Disposed on failure | Notes |
|---|---|---|---|
| One container in a top-level variable | No | No | State leaks between tests. Avoid it. |
| Container created inside each test, trailing `dispose()` | Yes | No | Skipped when the test throws. |
| Container created inside each test, `addTearDown(container.dispose)` | Yes | Yes | The default choice. |
| Container created in `setUp`, `addTearDown` in the same `setUp` | Yes | Yes | Good when many tests share the same setup. |
The setUp version is a convenience. It does not change the rule: one container per test.
Teardown order
When a test registers more than one teardown, they run in reverse order of registration, last registered first. This mirrors how nested resources are normally released: you close the inner thing before the outer one.
import 'package:flutter_test/flutter_test.dart';
void main() {
test('teardowns run last-in, first-out', () {
final log = <String>[];
addTearDown(() => log.add('first registered'));
addTearDown(() => log.add('second registered'));
expect(log, isEmpty);
// After this test ends, the teardowns run:
// 'second registered' runs before 'first registered'.
});
}This matters when containers depend on each other. If you create a child container with ProviderContainer(parent: parent), register the parent's teardown first and the child's second. The child is then disposed before the parent, which is the safe order.
Where addTearDown can be called
addTearDown belongs to the test framework, and it can only run while a test, setUp, or similar hook is executing. Calling it at the top level of main or inside a group body, outside any setUp or test, throws an error because there is no current test to attach the callback to.
void main() {
// Wrong: there is no running test here.
// addTearDown(() {});
setUp(() {
// Right: runs as part of each test.
addTearDown(() {});
});
}Overrides are part of creation
Overrides are passed when you create the container, so they follow the same rule: each test builds the container it needs, with exactly the overrides it needs.
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
addTearDown(container.dispose);Overrides cannot be changed after a container exists. If a test needs different fakes, create a different container, which costs almost nothing. Later chapters cover overrides in detail.
Widget tests are different
In a widget test, you normally do not create a container yourself. ProviderScope creates one when it is mounted and disposes it when it is removed from the widget tree. That means the per-test container rule is met automatically as long as each test pumps its own ProviderScope. If you need to read providers from outside the widget tree in a widget test, you can fetch the scope's container with ProviderScope.containerOf(context). Do not dispose that one yourself.
Common mistakes
- Creating the container but forgetting
addTearDown. Tests pass, but resources leak. The leak shows up later as flaky timers or streams. - Calling
addTearDown(container.dispose()). The parentheses calldisposeimmediately and pass its result,void, toaddTearDown. Pass the tear-offcontainer.dispose. - Registering teardown late. Register it on the line after creation, before reading anything.
- Reusing a container across tests "for speed". Containers are cheap. Shared state costs far more in debugging time.
- Using a container after its test ended. For example, a callback fires from an async operation after teardown. Await your futures before the test returns, so disposal comes last.
Exercise
A teammate writes this test. It sometimes leaves a timer running after a failed expectation. What is wrong, and how would you fix it? test('loads data', () { final container = ProviderContainer(); expect(container.read(dataProvider), isNotNull); container.dispose(); });
Show answer
The trailing container.dispose() is skipped when the expect fails or anything above it throws, so the container and the resources its providers hold (such as a timer started in the provider) are never released. Register the disposal right after creating the container: addTearDown(container.dispose); and remove the trailing call. The teardown then runs however the test ends.
Exercise
You have a group with five tests that each need a fresh container. Where do you create it, and which variable declaration do you use for it: late final or late?
Show answer
Create it in setUp, so it runs before every test, and call addTearDown(container.dispose) in the same setUp so each test disposes its own container. Declare the variable as late ProviderContainer container, not late final. A final variable can be assigned only once, but setUp assigns it again for every test.
Exercise
What is the difference between addTearDown(container.dispose) and addTearDown(container.dispose())?
Show answer
The first passes the dispose method as a function, so the test framework calls it after the test ends. The second calls dispose immediately, while the test is still starting, and passes its void result to addTearDown. That disposes the container before the test body uses it, and it leaves nothing valid to register as a teardown.