Sub topic 3
Overriding providers with ProviderScope
This chapter assumes you know ProviderScope, ConsumerWidget, and ref.watch, and that you have already run build_runner in a project that uses @riverpod.
Replacing a provider with ProviderScope
The overrides list of ProviderScope swaps out how a provider builds its value. The replacement applies to every widget below that scope. Use this to inject a different implementation of a dependency, such as a fake repository.
void main() {
runApp(
ProviderScope(
overrides: [
userRepositoryProvider.overrideWith((ref) => FakeUserRepository()),
],
child: const MyApp(),
),
);
}Replacing dependencies in tests
ProviderContainer accepts the same overrides list, so a unit test can run without a ProviderScope or any widgets.
import 'package:flutter_test/flutter_test.dart';
test('loads the user from the repository', () async {
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWith((ref) => FakeUserRepository()),
],
);
addTearDown(container.dispose);
final user = await container.read(userProvider(1).future);
expect(user.id, 1);
});Scoped providers for subtrees such as list items
A provider can throw by default and receive its real value from a nested ProviderScope. Listing the base provider in dependencies tells Riverpod that the derived provider reads the scoped value.
@Riverpod(dependencies: [])
Item currentItem(Ref ref) =>
throw UnimplementedError('Override currentItemProvider in a ProviderScope');
@Riverpod(dependencies: [currentItem])
String currentItemTitle(Ref ref) => ref.watch(currentItemProvider).title;Pitfalls: stale generated code, unstable arguments, missing dependencies
| Pitfall | Symptom | Fix |
|---|---|---|
| Stale generated code | New annotations or renamed functions do not take effect | Run `dart run build_runner build` again, or keep `build_runner watch` running |
| Unstable family arguments | Each rebuild creates a new provider instance | Define `==` and `hashCode` on the argument class |
| Missing dependencies | A scoped override is ignored by a derived provider | List the base provider in `dependencies: [...]` |
Exercise
A list item tile reads currentItemTitle, but the title always shows the default error. Which two changes fix it, and why?
Show answer
Wrap each tile in a ProviderScope that overrides currentItemProvider, and make sure currentItemTitle lists currentItem in its dependencies. The override supplies the item, and the dependencies entry tells Riverpod that the derived title must be recomputed from that scoped value.