Sub topic 1
Why test providers with a ProviderContainer
Riverpod providers hold your app's state and logic. That logic can be tested without drawing a single widget. This chapter explains why a ProviderContainer is the right tool for the job, what it does, and how a first test looks. Later chapters build on it with overrides, async providers, listening and auto-dispose behavior.
Prerequisites
This chapter assumes you already know:
- Dart and Flutter basics, including classes, generics and
finaltop-level variables. - How to write tests with
package:testorflutter_test:test,expect,groupandaddTearDown. - Basic Riverpod usage:
Provider,FutureProvider,NotifierProvider, and the difference betweenref.watchandref.read. async/awaitandFuturein Dart.
The examples use flutter_riverpod 2.x with the Notifier API. They run with flutter test.
The problem: testing logic through widgets is slow and indirect
Suppose a counter's logic lives in a notifier. The most obvious way to test it is a widget test. You pump a widget tree wrapped in a ProviderScope, tap a button, and look for text on screen.
That works, but it tests several things at once:
- the provider logic,
- the widget that displays it,
- the layout and finder code that locates the widget,
- the framework's scheduling of frames.
When such a test fails, you don't know which layer is at fault. These tests are also slower and need more setup than a plain Dart test. Most of the code you want to verify (state transitions, error handling, calls to repositories) never needed a widget in the first place.
A ProviderContainer lets you skip the widget layer. You create it in a test, read providers from it, call methods on notifiers, and assert on the results. The test is a plain synchronous or async Dart function.
What a ProviderContainer is
A provider declaration such as this one is only a description:
final counterProvider = NotifierProvider<Counter, int>(Counter.new);It says how to build a value. It does not hold the value. The value, along with its cached state and its subscriptions, lives inside a ProviderContainer.
In a running app, ProviderScope creates one container for you and exposes it to the widget tree. In a test, you create the container yourself. That is the whole idea: the container is the same object the app uses, minus the widgets.
| Concept | In the app | In a plain Dart test |
|---|---|---|
| Where provider state lives | The container inside `ProviderScope` | A `ProviderContainer` you create |
| Who reads providers | Widgets through `WidgetRef` | Your test, through `container.read` |
| Who disposes state | The scope, when it leaves the tree | Your test, through `container.dispose` |
| Where overrides go | `ProviderScope(overrides: ...)` | `ProviderContainer(overrides: ...)` |
Because overrides use the same list type in both places, a test double written for a container test can be reused unchanged in a widget test later.
A first test
This test creates a container, reads the initial state, calls a notifier method, and checks the new state.
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);
});
}Walk through it line by line:
ProviderContainer()creates an empty container. No provider has been built yet, because providers are lazy.addTearDown(container.dispose)schedules cleanup. The test framework runs it after the test finishes, whether the test passed or failed.container.read(counterProvider)builds the notifier by callingbuild(), caches the result, and returns0.container.read(counterProvider.notifier)returns theCounterinstance. Callingincrement()on it changesstate.- The second
container.read(counterProvider)returns the updated value,1.
Nothing here needed pumpWidget, a Finder or a BuildContext. The test runs in a few milliseconds.
Why this approach works well
The test targets one layer
The test calls the same notifier methods your widgets call. If the test fails, the bug is in the provider or something it depends on. If a widget test fails later, you can rule out the provider logic.
State is isolated per container
State belongs to the container, not to the provider variable. The top-level counterProvider is shared by the whole program, but each container keeps its own value for it. You can see this directly:
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('two containers keep separate state', () {
final a = ProviderContainer();
final b = ProviderContainer();
addTearDown(a.dispose);
addTearDown(b.dispose);
a.read(counterProvider.notifier).increment();
expect(a.read(counterProvider), 1);
expect(b.read(counterProvider), 0);
});
}This isolation is what lets tests run independently. A new container per test means one test cannot leave state behind for the next.
Dependencies can be replaced
Providers usually depend on other providers: a repository, an HTTP client, a clock. A container accepts overrides, a list that replaces some providers with test versions. The code under test then runs against a fake instead of the network. Chapters on overrides and fakes cover this in detail. Here is a preview:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.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 = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
addTearDown(container.dispose);
final name = await container.read(userNameProvider.future);
expect(name, 'Ada');
});
}Two details matter here. The real userRepositoryProvider throws UnimplementedError if nobody overrides it, so a test that forgets the override fails loudly instead of reaching for a real data source. And reading .future returns a Future<String> you can await, which is how a test waits for an async provider.
You can observe state over time
Some behavior is a sequence, not a single final value. container.listen lets a test record every change. A later chapter shows how. For now, note that this is only possible because the container is an object you control, with the same subscription model widgets use.
The container lifecycle in brief
A container has a simple life: create, use, dispose.
- Create one per test. Creating one costs almost nothing.
- Use it by reading and listening. Providers are built the first time something reads them.
- Dispose it at the end. Disposal runs the providers'
ref.onDisposecallbacks, cancels subscriptions, and releases anything the providers hold, such as stream controllers or timers.
addTearDown is the standard place to register disposal, directly after creation. Registering it on the next line means you cannot forget it, and it still runs if an assertion throws halfway through the test.
final container = ProviderContainer();
addTearDown(container.dispose);A later chapter extracts these two lines into a helper, so every test gets them for free.
Common mistakes to avoid at this stage
Several errors show up even in simple container tests.
- Sharing one container between tests. If you declare a container at the top of
mainand reuse it, state from one test leaks into the next. Tests then pass or fail depending on their order. Create a container inside each test (or insetUp). - Forgetting to dispose. The test may still pass, but timers, streams and listeners stay alive. This causes confusing failures in unrelated tests, or tests that hang because the process never becomes idle.
- Trying to use
refin a test. A test body has noReforWidgetRef. Use the container:container.read,container.listen. These are the container's equivalents. - Reading a notifier's state through
.notifier.container.read(counterProvider.notifier)gives you the notifier object, which you call methods on.container.read(counterProvider)gives you the value. Mixing them up gives type errors or an unexpected object inexpect. - Not awaiting async providers. Calling
container.read(userNameProvider)on aFutureProviderreturns anAsyncValue, and right after creation that isAsyncLoading. To wait for the result,await container.read(userNameProvider.future).
When a container test is not enough
A container test proves the provider logic works. It does not prove that:
- a widget displays the right text for each state,
- a button calls the right notifier method,
- the widget tree rebuilds when the state changes.
Those need widget tests. The practical split is to put most of your coverage in fast container tests, then write fewer widget tests that check the UI wiring. Because ProviderScope takes the same overrides list as ProviderContainer, the fakes you build for the first kind of test carry over to the second.
What the rest of the tutorial covers
The remaining chapters take each piece of this one further:
- creating and disposing containers reliably,
- reading state and testing notifiers,
- overrides, fakes and mocks,
- async providers and error states,
- recording changes with
container.listen, - keeping auto-dispose providers alive during a test,
- a reusable
createContainerhelper, - moving the same overrides into widget tests,
- common pitfalls.
Exercise
A teammate declares final container = ProviderContainer(); at the top of main() in a test file and uses it in three tests. The tests pass when run together but one fails when run alone. What is the likely cause, and how would you fix it?
Show answer
The tests share state through the one container. A test that passes only after an earlier test has changed the state, or that fails because of a leftover value, depends on run order. Running one test alone removes the earlier changes. The fix is to create a new container inside each test (or in setUp) and register addTearDown(container.dispose) right after creating it. Each test then starts with fresh provider state.
Exercise
In a test, you call container.read(userNameProvider) on a FutureProvider<String> and compare the result with 'Ada' using expect. The test fails. Why, and what should you read instead?
Show answer
container.read(userNameProvider) returns an AsyncValue<String>, which is AsyncLoading right after the first read, not a String. To get the actual string, mark the test async and use await container.read(userNameProvider.future), which completes with 'Ada' once the fake repository returns.
Exercise
Why does the chapter's override example make the real userRepositoryProvider throw UnimplementedError, instead of returning a real repository?
Show answer
A provider that throws unless overridden forces every test (and the app's root scope) to supply an implementation. If a test forgets the override, it fails immediately with a clear message instead of silently calling a real network or database. It also keeps the production default out of tests.