Sub topic 1
Why Test Providers with a ProviderContainer
Prerequisites
This chapter assumes you know Dart and Flutter basics, can write tests with package:test or flutter_test (test, expect, addTearDown), and have used Provider, NotifierProvider, ref.watch, and ref.read in Riverpod.
Why test providers without widgets
Most of a Riverpod app's logic lives in providers. A provider holds state and decides how that state changes. If you test that logic through widgets, every failure becomes harder to trace. A widget test must build the widget tree, pump frames, and find buttons before it can check a single rule.
A ProviderContainer is the object that stores provider state and runs provider code. You can create one in a plain Dart test, with no widgets. That keeps tests fast and focused on one piece of logic.
One container per test, disposed with addTearDown
Create a new container for each test so that no state carries over from one test to the next. Register its cleanup with addTearDown, which runs after the test finishes, even if an assertion fails:
final container = ProviderContainer();
addTearDown(container.dispose);Calling dispose releases the providers and their listeners. Skipping it can leave state alive and make later tests behave differently depending on their order.
Reading provider state
Use container.read to get a provider's current value. To call a method on a Notifier, read its .notifier:
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('counter starts at zero and increments', () {
final container = ProviderContainer();
addTearDown(container.dispose);
expect(container.read(counterProvider), 0);
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
});
}> Note: container.read returns the current value once. It does not subscribe to changes.
Exercise
Exercise
In the example above, why does the test call addTearDown(container.dispose) instead of calling container.dispose() at the end of the test body?
Show answer
addTearDown runs the disposal even when an expect fails and the test stops early. A call at the end of the body would be skipped, which leaves the container's state alive.