Sub topic 10
Extracting a createContainer helper
Every test in this tutorial so far has started with the same two lines: create a ProviderContainer, then register container.dispose with addTearDown. This chapter turns those lines into one small helper. It also covers where the helper should live, how to extend it, and the mistakes that make it misbehave.
This chapter assumes you can write tests with flutter_test (test, group, setUp, addTearDown). It also assumes you know how ProviderContainer and overrides work from the earlier chapters.
Why repeat-free setup matters
Consider the pattern from the previous chapters:
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
addTearDown(container.dispose);Copied into fifty tests, this has three costs:
- Forgotten disposal. If one test omits
addTearDown, its container is never disposed. Notifiers and listeners stay alive, and any resources they hold (timers, streams, subscriptions) leak into later tests. The failure often shows up in a different test from the one that caused it. - Noise. The setup hides what each test is actually checking.
- Hard-to-change defaults. If you decide every test should also pass a shared observer, you must edit every test.
A helper puts creation and disposal in one place, so a test cannot create a container without scheduling its disposal.
The basic helper
The helper takes optional overrides, builds the container, registers disposal, and returns it.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
ProviderContainer createContainer({
ProviderContainer? parent,
List<Override> overrides = const [],
List<ProviderObserver>? observers,
}) {
final container = ProviderContainer(
parent: parent,
overrides: overrides,
observers: observers,
);
addTearDown(container.dispose);
return container;
}The helper exposes the constructor's three most useful parameters:
| Parameter | Purpose | Typical use in tests |
|---|---|---|
| `overrides` | Replace providers with fakes or fixed values | Isolating the code under test |
| `parent` | Create a child container that inherits from another | Testing scoped or layered containers |
| `observers` | Attach `ProviderObserver` objects | Logging or recording provider activity |
Most tests only ever pass overrides. Keep parent and observers so the helper never blocks a legitimate need, but do not add parameters you have no use for.
Where to put the file
Place the helper in a file under test/ that every test can import, for example test/helpers/create_container.dart. Files under test/ are not part of your app's lib/ code, so test-only code never ships to users.
Import it with a relative path from the test file:
import 'helpers/create_container.dart';A test at test/features/counter_test.dart would use ../helpers/create_container.dart instead.
The helper imports flutter_test because addTearDown comes from the test framework. If your package is pure Dart with no Flutter dependency, import package:test/test.dart instead. The helper's body does not change.
Using the helper in a test
Here is the counter test from the first chapter, rewritten to use the helper. The Counter and counterProvider definitions are repeated so the file runs as shown.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'helpers/create_container.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 = createContainer();
expect(container.read(counterProvider), 0);
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
});
}The disposal line is gone. The test now reads as arrange, act, assert, and the cleanup still happens after the test body finishes, whether it passes or fails.
With overrides
The helper keeps override lists short as well:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'helpers/create_container.dart';
abstract class UserRepository {
Future<String> fetchName();
}
final userRepositoryProvider = Provider<UserRepository>(
(ref) => throw UnimplementedError('Override userRepositoryProvider'),
);
final userNameProvider = FutureProvider<String>(
(ref) => ref.watch(userRepositoryProvider).fetchName(),
);
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName() async => 'Ada';
}
void main() {
test('userNameProvider returns the name from the repository', () async {
final container = createContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
final name = await container.read(userNameProvider.future);
expect(name, 'Ada');
});
}What happens when the test runs
The helper relies on the order in which the test framework runs your code. addTearDown does not dispose anything immediately. It queues a callback that runs after the current test finishes.
Two consequences follow from this order:
- The container stays usable for the whole test body, including any
awaitcalls. - Disposal runs even when an
expectfails, because teardown callbacks run after both passing and failing tests.
Using the helper with group and setUp
When many tests in a group share the same overrides, build the container in setUp. Calling addTearDown inside setUp is allowed, so the helper works there too.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'helpers/create_container.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 = createContainer();
});
test('starts at zero', () {
expect(container.read(counterProvider), 0);
});
test('increments once', () {
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
});
test('does not see state from the previous test', () {
expect(container.read(counterProvider), 0);
});
});
}setUp runs before each test in the group, so each test gets a new container. The last test proves it: the previous test incremented the counter, yet this one still reads 0.
The late variable is assigned fresh each time. Do not initialize it once outside setUp and share it across tests, which is the shared-container pitfall covered below.
Use setUp when several tests need identical wiring. Create the container inside the test body when a test needs its own overrides. Mixing both styles in one file is fine.
Extending the helper
A helper is a good place for defaults that every test needs, as long as they stay invisible and harmless. Two reasonable extensions:
- A default observer list. If you have a
ProviderObserverthat logs provider activity, pass it throughobserversin one place, so every test benefits when you debug. - A fixed set of base overrides. If every test needs the same fake for a platform service (say, a clock), add it inside the helper and append the caller's overrides after it.
Here is the second idea:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
final clockProvider = Provider<DateTime Function()>((ref) => DateTime.now);
ProviderContainer createAppContainer({
List<Override> overrides = const [],
}) {
final container = ProviderContainer(
overrides: [
clockProvider.overrideWithValue(() => DateTime.utc(2025, 1, 1)),
...overrides,
],
);
addTearDown(container.dispose);
return container;
}When two overrides target the same provider in one list, the later one wins. That is why the caller's overrides come last: a test can replace the default clock without editing the helper.
Keep the plain createContainer as well. A helper with hidden defaults makes tests shorter, but a reader must know the defaults exist. If you add many, tests become harder to understand on their own.
A note on newer Riverpod versions
Riverpod 3 includes a built-in ProviderContainer.test() constructor that does the same job: it creates a container and registers its disposal with the test framework. If your project uses a version that has it, you can use it instead of writing the helper. Check your package version, because the constructor does not exist in Riverpod 2. The helper in this chapter works in both, and it is still useful when you want to add your own defaults.
Pitfalls
Other problems to watch for:
- A container shared across tests. A single top-level
final container = createContainer()outlives the test it was created for, and its state carries into the next test. Tests then pass or fail depending on order. Always make a new container per test. - Disposing twice. If you also call
container.dispose()yourself at the end of the test, the teardown will call it again. Disposing an already disposed container can raise an error in some versions. Rely on the helper and remove the manual call. - Using the container after the test. A callback that fires after the test ends (an unawaited future, for example) may touch a disposed container. Await your futures inside the test so everything finishes before teardown.
- Hiding too much in the helper. If the helper registers many overrides, a test may pass because of a default that the reader cannot see. Prefer explicit overrides in the test when they matter to the behavior being checked.
Summary of the pattern
- Write
createContaineronce undertest/helpers/. - Call it from inside
testorsetUp, never at the top level. - Pass
overridesfor each test's fakes. - Do not call
disposeyourself.
Exercise
A teammate writes final container = createContainer(); as the first line inside group('Counter', () { ... }), outside any test or setUp, and the test run fails with an error about addTearDown. Why does it fail, and how do you fix it?
Show answer
addTearDown can only be called while a test or setUp is running. Code directly inside group runs when the tests are being registered, before any test exists, so there is nothing to attach the teardown to. Fix it by declaring late ProviderContainer container; in the group and assigning container = createContainer(); inside setUp, or by calling createContainer() inside each test body.
Exercise
You extend a helper so it always adds a fake clock override first, then spreads the caller's overrides after it. A test passes its own override for the same clock provider. Which one is used, and why does the order in the list matter?
Show answer
The test's override is used. When two overrides target the same provider in one list, the later entry wins. Putting the caller's overrides last lets each test replace the helper's default without changing the helper.
Exercise
Write a createContainer helper that accepts only overrides (defaulting to an empty list) and guarantees the container is disposed after the test.
Show answer
ProviderContainer createContainer({List<Override> overrides = const []}) { final container = ProviderContainer(overrides: overrides); addTearDown(container.dispose); return container; }