Sub topic 3
Reading provider state
This chapter covers how container.read works in a test: when it creates state, what it returns, and how to read each kind of provider. It assumes you can write test and expect cases, you know the basic provider types (Provider, FutureProvider, NotifierProvider), and you know await in Dart. The previous chapter showed how to create a container and dispose it with addTearDown. Here you use that container to look at state.
What `container.read` does
container.read(provider) returns the provider's current value. If the provider has not been used yet, the container creates it first by running its build function. It then stores the result and returns it. Later reads return the stored value without running the build function again.
This has two consequences for tests:
- State is created lazily. Nothing is built until a test reads it, or reads something that depends on it.
- State is cached per container. Two containers never share state, which is why one container per test gives you isolation.
Proving the lazy, cached behavior
The test below counts build calls with a local variable. It also uses container.exists, which reports whether a provider has state in the container without creating it.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('read builds once and caches the result', () {
var buildCount = 0;
final greetingProvider = Provider<String>((ref) {
buildCount++;
return 'hello';
});
final container = ProviderContainer();
addTearDown(container.dispose);
expect(container.exists(greetingProvider), isFalse);
expect(buildCount, 0);
expect(container.read(greetingProvider), 'hello');
expect(container.read(greetingProvider), 'hello');
expect(container.exists(greetingProvider), isTrue);
expect(buildCount, 1);
});
}Declaring the provider inside the test is fine here because it needs to capture buildCount. In real code, providers are top-level final variables.
Reading a provider also builds everything it depends on. If userNameProvider calls ref.watch(userRepositoryProvider), reading the first one creates the second.
Reading a value is taking a snapshot
read returns the value as it is at that moment. If you store it in a variable, the variable does not update when state changes. This matters most for notifiers.
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('a stored value does not follow later changes', () {
final container = ProviderContainer();
addTearDown(container.dispose);
final before = container.read(counterProvider);
container.read(counterProvider.notifier).increment();
final after = container.read(counterProvider);
expect(before, 0);
expect(after, 1);
});
}To check a value after an action, call read again after the action. Never reuse the earlier result. To see every intermediate value, use container.listen, which a later chapter covers.
Two things to read from a notifier provider
A NotifierProvider exposes two different things, and each has its own read:
| Expression | Returns | Use it to |
|---|---|---|
| `container.read(counterProvider)` | The state (`int` here) | Assert on the current value |
| `container.read(counterProvider.notifier)` | The `Counter` instance | Call methods such as `increment()` |
The notifier instance stays the same for as long as the provider's state is alive, so you can read it once and keep the reference:
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('the notifier instance is stable', () {
final container = ProviderContainer();
addTearDown(container.dispose);
final notifier = container.read(counterProvider.notifier);
notifier.increment();
notifier.increment();
expect(identical(notifier, container.read(counterProvider.notifier)), isTrue);
expect(container.read(counterProvider), 2);
});
}Reading .notifier also builds the provider, so the state is initialized by the time you call a method.
Reading async providers
A FutureProvider exposes an AsyncValue<T> as its state. That value is one of three cases: loading, data, or error. A read right after the first access returns the loading case, because the future has not finished.
There are two ways to read an async provider:
| Expression | Returns | Typical use |
|---|---|---|
| `container.read(userNameProvider)` | `AsyncValue<String>` | Check loading, data, or error state at this moment |
| `container.read(userNameProvider.future)` | `Future<String>` | `await` the result |
The next test uses a fake repository. It checks the loading state, awaits the future, and reads the AsyncValue again.
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('read shows loading first, then data', () async {
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
addTearDown(container.dispose);
expect(container.read(userNameProvider).isLoading, isTrue);
final name = await container.read(userNameProvider.future);
expect(name, 'Ada');
expect(container.read(userNameProvider).requireValue, 'Ada');
});
}The first read starts the fetch, and .future then gives you the same in-flight request, not a second one. The overrides in this example are covered in the next chapter. For now, treat them as the way to supply a fake repository.
For the error path, await on .future throws the original error. Use expectLater so the test waits for the assertion to finish:
class FailingUserRepository implements UserRepository {
@override
Future<String> fetchName() async => throw Exception('offline');
}
void main() {
test('read of .future surfaces the error', () async {
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FailingUserRepository()),
],
);
addTearDown(container.dispose);
await expectLater(
container.read(userNameProvider.future),
throwsA(isA<Exception>()),
);
expect(container.read(userNameProvider).hasError, isTrue);
});
}This snippet reuses the declarations from the previous example, plus the same imports.
Reading providers that take parameters
A family provider creates separate state for each argument. Reading greetingProvider('Ada') and greetingProvider('Grace') builds two independent entries in the same container.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
final greetingProvider = Provider.family<String, String>(
(ref, name) => 'Hello, $name',
);
void main() {
test('each family argument has its own state', () {
final container = ProviderContainer();
addTearDown(container.dispose);
expect(container.read(greetingProvider('Ada')), 'Hello, Ada');
expect(container.read(greetingProvider('Grace')), 'Hello, Grace');
expect(container.exists(greetingProvider('Ada')), isTrue);
});
}Family arguments are compared with ==. Use values with sensible equality, such as strings, numbers, or classes that override ==. If you pass a new object without == on each call, each read creates a new entry.
Forcing a rebuild: invalidate and refresh
Sometimes a test needs to throw away cached state and build again. The container has two methods for this:
container.invalidate(provider)marks the state as stale. The next read rebuilds it.container.refresh(provider)rebuilds immediately and returns the new value.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('invalidate and refresh rebuild the provider', () {
var calls = 0;
final callsProvider = Provider<int>((ref) => ++calls);
final container = ProviderContainer();
addTearDown(container.dispose);
expect(container.read(callsProvider), 1);
expect(container.read(callsProvider), 1);
container.invalidate(callsProvider);
expect(container.read(callsProvider), 2);
expect(container.refresh(callsProvider), 3);
});
}In most tests you will not need either method. A fresh container per test already gives you fresh state. They are useful when you are testing code that itself calls ref.invalidate or ref.refresh, and you want to confirm the rebuild happens.
Reading a provider that throws
If a synchronous provider's build function throws, container.read throws. This is also what happens when you forget an override for a provider written to throw UnimplementedError, as userRepositoryProvider is above.
void main() {
test('reading a provider without its override fails', () {
final container = ProviderContainer();
addTearDown(container.dispose);
expect(
() => container.read(userRepositoryProvider),
throwsA(anything),
);
});
}This test also reuses the declarations above.
This explains a common first failure: a test throws on its first read with a message like "Override userRepositoryProvider". The code is fine. The test is missing an override.
Choosing between read, listen, and exists
All three methods look at a container, but they have different jobs.
| Method | Creates state? | Returns | Best for |
|---|---|---|---|
| `container.read(p)` | Yes | Current value | Asserting on state at one moment |
| `container.listen(p, ...)` | Yes | A subscription | Recording changes over time, keeping state alive |
| `container.exists(p)` | No | `bool` | Checking whether state was built or disposed |
Inside providers and widgets, the guidance is "use ref.watch to depend on a value, and ref.read only for one-off actions." A test is not a provider, so that rule does not apply. A test is a one-off observer, so container.read is the normal tool.
Common mistakes when reading state
- Reading before overriding. Overrides are given when the container is created. Create the container with the overrides, then read.
- Asserting on a stale variable. Re-read after each action, as shown above.
- Asserting on
AsyncValuetoo early. AFutureProviderread right after creation is loading. Await.futurebefore you check for data or error. - Not awaiting. Calling
expect(container.read(p.future), throwsA(...))withoutexpectLaterandawaitlets the test finish before the assertion runs. - Sharing a container across tests. State from one test leaks into the next, so tests pass or fail depending on their order.
Exercises
Exercise
A test reads final value = container.read(counterProvider);, then calls container.read(counterProvider.notifier).increment();, and finally asserts expect(value, 1);. The assertion fails with 0. Why, and how do you fix it?
Show answer
read returns a snapshot of the state at the time of the call. The variable value holds the old 0 and does not update when the notifier changes state. Call container.read(counterProvider) again after increment() and assert on that result: expect(container.read(counterProvider), 1);.
Exercise
You write final provider = FutureProvider<int>((ref) async => 7); and then expect(container.read(provider).value, 7); as the first read. The assertion fails. What do you change?
Show answer
The first read returns the loading state, so value is null. Await the future first: await container.read(provider.future);. After that, container.read(provider).requireValue returns 7.