Sub topic 12
Pitfalls: shared containers, unawaited futures, and leaked state
This chapter collects the mistakes that most often make Riverpod provider tests flaky, slow, or misleading. It assumes you can write tests with flutter_test (test, expect, group, addTearDown). It also assumes you know Provider, FutureProvider, and NotifierProvider, the createContainer helper from earlier in this tutorial, and async/await in Dart.
Every pitfall below has the same root: a provider's state lives in a ProviderContainer, not in the provider declaration. If you get the container's lifetime or timing wrong, your tests read state they did not set up, or they check state before it exists.
The helper used throughout is the one from the previous chapter:
ProviderContainer createContainer({List<Override> overrides = const []}) {
final container = ProviderContainer(overrides: overrides);
addTearDown(container.dispose);
return container;
}Pitfall 1: Sharing one container across tests
Provider declarations are global final variables, so it is tempting to share a container too. Tests then pass or fail depending on which ones ran before them.
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() {
final container = ProviderContainer(); // shared by every test below
tearDownAll(container.dispose);
test('increments', () {
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
});
test('starts at zero', () {
// Fails: the previous test left the state at 1.
expect(container.read(counterProvider), 0);
});
}Run alone, the second test passes. Run after the first, it fails. With --shuffle or --plain-name, the result changes again. The fix is one container per test, created through createContainer:
void main() {
test('increments', () {
final container = createContainer();
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
});
test('starts at zero', () {
final container = createContainer();
expect(container.read(counterProvider), 0);
});
}If you prefer setUp, declare late ProviderContainer container; and assign it inside setUp, calling addTearDown(container.dispose) there too. Never assign it at the top of main or in a group body, because those lines run once, not once per test.
Pitfall 2: Not disposing the container
A container that is never disposed never runs the cleanup callbacks registered with ref.onDispose. Streams stay open, timers keep firing, and listeners stay attached. The leak may only show up as a hanging test run or as output from a later test.
import 'dart:async';
final controllerProvider = Provider<StreamController<int>>((ref) {
final controller = StreamController<int>();
ref.onDispose(controller.close);
return controller;
});
void main() {
test('disposing the container runs onDispose callbacks', () {
final container = ProviderContainer();
final controller = container.read(controllerProvider);
expect(controller.isClosed, isFalse);
container.dispose();
expect(controller.isClosed, isTrue);
});
}This test calls container.dispose() itself so it can observe the effect. In ordinary tests, register disposal with addTearDown at the moment you create the container. A manual dispose() at the end of a test is skipped when an earlier expect fails, and then the leak affects the following tests. addTearDown runs either way.
The reverse mistake also exists. Once a container is disposed, reading from it throws a StateError. This happens when a callback, such as an unawaited future, touches the container after the test body returns and teardown has run.
Pitfall 3: Unawaited futures
Async code has two common failure modes in provider tests. Both come from checking state before the work has finished.
Reading a FutureProvider synchronously
container.read(userNameProvider) returns an AsyncValue, not the result. On the first read the provider has only just started, so the value is AsyncLoading.
final userNameProvider = FutureProvider<String>((ref) async => 'Ada');
void main() {
test('wrong: reads the AsyncValue before the future completes', () {
final container = createContainer();
final value = container.read(userNameProvider);
expect(value, isA<AsyncLoading<String>>()); // not AsyncData
});
test('right: awaits the future', () async {
final container = createContainer();
final name = await container.read(userNameProvider.future);
expect(name, 'Ada');
});
}Always await the .future property when you want the result. If you want to assert on the AsyncValue itself (for example, to check that AsyncLoading comes first), read the value synchronously, then await .future, then read it again.
Calling an async notifier method without await
A notifier method that returns a Future must be awaited, or your assertion runs while the method is still in progress.
class Loader extends Notifier<String> {
@override
String build() => 'idle';
Future<void> load() async {
state = 'loading';
await Future<void>.delayed(const Duration(milliseconds: 10));
state = 'done';
}
}
final loaderProvider = NotifierProvider<Loader, String>(Loader.new);
void main() {
test('wrong: asserts while load() is still running', () {
final container = createContainer();
container.read(loaderProvider.notifier).load(); // not awaited
expect(container.read(loaderProvider), 'loading');
});
test('right: awaits load()', () async {
final container = createContainer();
await container.read(loaderProvider.notifier).load();
expect(container.read(loaderProvider), 'done');
});
}The first test passes, which makes it worse than a failing one. It asserts an intermediate state and ignores the rest. Meanwhile the unawaited future is still running when the test ends. The container is then disposed, and when the delay finishes, the method sets state on a disposed notifier, which can throw a StateError in a place unrelated to the test that caused it. The Dart analyzer lint unawaited_futures catches this pattern. Enable it in analysis_options.yaml.
Asserting on errors without waiting
Use await expectLater(...) with throwsA when testing the error path of a future:
await expectLater(
container.read(userNameProvider.future),
throwsA(isA<Exception>()),
);A plain expect with a future and throwsA also works, but the next line of the test runs before the future settles. With expectLater and await, the order is explicit.
Pitfall 4: Auto-dispose state disappearing
An auto-dispose provider is disposed when it has no listeners. container.read does not count as a listener. The disposal is scheduled, so a purely synchronous test can seem fine, while a test that yields to the event loop sees the state reset.
final autoCounterProvider =
NotifierProvider.autoDispose<Counter, int>(Counter.new);
void main() {
test('wrong: state resets once the test awaits', () async {
final container = createContainer();
container.read(autoCounterProvider.notifier).increment();
await Future<void>.delayed(Duration.zero);
expect(container.read(autoCounterProvider), 0); // incremented value is gone
});
test('right: a listener keeps the provider alive', () async {
final container = createContainer();
final subscription = container.listen(autoCounterProvider, (_, __) {});
addTearDown(subscription.close);
container.read(autoCounterProvider.notifier).increment();
await Future<void>.delayed(Duration.zero);
expect(container.read(autoCounterProvider), 1);
});
}The first test asserts the reset only to show the behavior. In your own tests, a surprising 0 or AsyncLoading in the middle of an async test usually means a missing listener. This matters most for auto-dispose FutureProviders whose work spans several awaits: without a listener, the provider can be disposed and restarted partway through.
Pitfall 5: State leaking through fakes and globals
A fresh container does not protect you from shared Dart objects. A fake stored in a top-level variable or a static field keeps its state across tests, even though every container is new.
abstract class UserRepository {
Future<String> fetchName();
}
final userRepositoryProvider = Provider<UserRepository>(
(ref) => throw UnimplementedError('Override userRepositoryProvider'),
);
class FakeUserRepository implements UserRepository {
int calls = 0;
@override
Future<String> fetchName() async {
calls++;
return 'Ada';
}
}
final sharedFake = FakeUserRepository(); // leaks calls between testsIf two tests both use sharedFake and assert calls == 1, the second one fails. Create the fake inside the test, or inside setUp:
void main() {
test('fetches the name once', () async {
final fake = FakeUserRepository();
final container = createContainer(
overrides: [userRepositoryProvider.overrideWithValue(fake)],
);
final userNameProvider = FutureProvider<String>(
(ref) => ref.watch(userRepositoryProvider).fetchName(),
);
await container.read(userNameProvider.future);
expect(fake.calls, 1);
});
}The same applies to mutable lists or maps captured by a fake, and to static counters. Anything that outlives one test must be reset in setUp.
Pitfall 6: A forgotten override
The userRepositoryProvider above deliberately throws UnimplementedError when it is not overridden. This is a good pattern, because a test that forgets the override fails loudly instead of reaching a real network or database. Do not "fix" the error by giving the provider a real default. If you see UnimplementedError: Override userRepositoryProvider in a test, the container was created without the override. This often happens when a test uses ProviderContainer() directly instead of createContainer(overrides: [...]).
Diagnosing a failing test
Match the symptom to the likely cause before you change the test:
The same information in a table:
| Symptom | Likely cause | Fix |
|---|---|---|
| Passes alone, fails in the full suite | Shared container, or a shared fake or static field | One container and fresh fakes per test |
| `AsyncLoading` where you expected data | Read `AsyncValue` before the future finished | `await container.read(p.future)` |
| Assertion sees `'loading'` or another intermediate value | Notifier method not awaited | `await` the method call |
| State reverts to its initial value after an `await` | Auto-dispose provider with no listener | Keep a `container.listen` subscription open |
| `UnimplementedError` from a repository provider | Override missing | Pass `overrides` to `createContainer` |
| `StateError` after the test ends | Work still running after disposal | Await all work before the test returns |
| Test run hangs or logs from earlier tests | Container never disposed | `addTearDown(container.dispose)` at creation |
A pre-commit checklist for provider tests
- Is the container created inside the test or
setUp, not at the top ofmain? - Is
addTearDown(container.dispose)called right where the container is created? - Is every
Futureeither awaited or intentionally ignored? - Does every auto-dispose provider that spans an
awaithave a listener? - Are fakes created per test, with no static state?
- Does the test fail when you break the code under test? Temporarily invert one assertion or change the production code to confirm.
Exercise
A test creates a container, calls container.read(loaderProvider.notifier).load() without await, then asserts the state is 'done'. It fails with 'loading'. A teammate suggests adding await Future<void>.delayed(const Duration(milliseconds: 50)) before the expect. Why is that the wrong fix, and what should you do instead?
Show answer
The delay guesses how long load() takes, so the test becomes slow and breaks if the timing changes. The real problem is that the future returned by load() is ignored. Write await container.read(loaderProvider.notifier).load(); so the test continues exactly when the method finishes.
Exercise
Two tests use the same top-level final fake = FakeUserRepository(); with a calls counter, and each creates its own container through createContainer. The second test asserting calls == 1 fails. The containers are separate, so what is shared, and how do you fix it?
Show answer
The fake object is shared, even though the containers are separate. Its calls field keeps counting across tests. Create the fake inside each test, or reassign it in setUp, so every test starts with a fresh instance.
Exercise
An auto-dispose FutureProvider test passes when it contains no await before the assertion but fails when you add await Future<void>.delayed(Duration.zero). State the cause and the fix.
Show answer
Reading with container.read does not keep an auto-dispose provider alive. Yielding to the event loop lets the scheduled disposal run, so the state resets. Open a subscription with container.listen(provider, (_, __) {}) at the start of the test and close it with addTearDown(subscription.close).