Sub topic 11
Dependency injection with Riverpod
This chapter assumes you know Dart abstract classes and implements, async/await, and the idea of a repository that a view model depends on. It also assumes you have seen constructor injection and the Provider package from earlier chapters. Here you will see how Riverpod covers the same ground, where it differs from Provider and get_it, and what goes wrong when you use it carelessly.
How Riverpod relates to dependency injection
Riverpod is a state management library, but its core mechanism is a dependency container. You declare a provider, which is a description of how to build a value. A container (ProviderContainer) builds the value on demand, caches it, and hands it to anyone who asks.
Three properties make it work as dependency injection:
- Providers are declarations, not instances. A top-level
final userRepositoryProvider = ...looks like a global variable. It is only a key plus a recipe. The actualUserRepositorylives inside a container. - Dependencies are explicit. One provider reads another through
ref, so the dependency graph is visible in code and Riverpod can rebuild or dispose parts of it correctly. - Any provider can be overridden. When you create a container, you can replace a provider's recipe. Every consumer then receives the replacement, and none of their code changes.
Unlike Provider, Riverpod does not depend on BuildContext to find a value. Provider looks up the widget tree and throws a ProviderNotFoundException at runtime if the type is missing. Riverpod looks up a provider object, so a missing registration is a compile-time error.
Declaring the repository as a provider
The abstraction is the same one used in the earlier chapters. The provider exposes it by its abstract type, so consumers never name the concrete class.
import 'package:riverpod/riverpod.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async {
// Call the real backend here.
return 'User $id';
}
}
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Test User';
}
final userRepositoryProvider = Provider<UserRepository>(
(ref) => ApiUserRepository(),
);
final userNameProvider = FutureProvider.family<String, int>(
(ref, id) => ref.watch(userRepositoryProvider).fetchName(id),
);
void main() async {
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
final name = await container.read(userNameProvider(1).future);
print(name); // Test User
container.dispose();
}userNameProvider is a provider that depends on userRepositoryProvider. It declares that dependency by calling ref.watch inside its body. It never constructs a repository and never learns which implementation it got. Removing the overrides list makes main print User 1 instead.
The .family modifier gives the provider a parameter. userNameProvider(1) and userNameProvider(2) are separate cached entries in the container.
The container and the object graph
The next diagram shows what happens when a consumer asks for a value.
The container is the composition root in this design. In a Flutter app you create it implicitly with ProviderScope.
Using providers in Flutter
Wrap the app in ProviderScope, then read providers from a ConsumerWidget.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
runApp(const ProviderScope(child: MaterialApp(home: ProfilePage(id: 1))));
}
class ProfilePage extends ConsumerWidget {
const ProfilePage({super.key, required this.id});
final int id;
@override
Widget build(BuildContext context, WidgetRef ref) {
final name = ref.watch(userNameProvider(id));
return Scaffold(
body: Center(
child: name.when(
data: (value) => Text(value),
loading: () => const CircularProgressIndicator(),
error: (error, _) => Text('Error: $error'),
),
),
);
}
}This code assumes the providers from the previous section are in scope. The FutureProvider returns an AsyncValue<String>, so the widget handles the loading, data, and error states with when. There is no FutureBuilder and no manual notifyListeners.
Injecting into a notifier
When logic outgrows a plain provider, use a Notifier or AsyncNotifier. This class plays the role that ProfileViewModel played in the earlier chapters. It receives its dependency through ref instead of through a constructor argument.
import 'package:riverpod/riverpod.dart';
class ProfileController extends AsyncNotifier<String> {
@override
Future<String> build() => ref.watch(userRepositoryProvider).fetchName(1);
Future<void> reload(int id) async {
final repository = ref.read(userRepositoryProvider);
state = const AsyncLoading();
state = await AsyncValue.guard(() => repository.fetchName(id));
}
}
final profileControllerProvider =
AsyncNotifierProvider<ProfileController, String>(ProfileController.new);The choice between ref.watch and ref.read matters here:
- Use
ref.watchinbuildand in provider bodies. If the watched provider changes, for example because of an override or an invalidation, the notifier rebuilds with the new dependency. - Use
ref.readin event handlers and methods such asreload. Reading is a one-time lookup and does not subscribe to changes.
If you prefer plain constructor injection, you can still do it. Write ProfileViewModel(ref.watch(userRepositoryProvider)) inside a provider body, and the view model stays free of any Riverpod import. This is useful when you want domain classes to be testable without a container at all.
Overrides in tests
Overrides are Riverpod's replacement for hand-wiring fakes. There are two common forms.
| Form | Use it when |
|---|---|
| `overrideWithValue(fake)` | You already have the fake instance and want a fixed value. |
| `overrideWith((ref) => ...)` | The replacement needs `ref`, or must be built lazily or differently per test. |
A unit test needs no Flutter, only a container:
import 'package:flutter_test/flutter_test.dart';
import 'package:riverpod/riverpod.dart';
void main() {
test('userNameProvider uses the overridden repository', () async {
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
addTearDown(container.dispose);
final name = await container.read(userNameProvider(1).future);
expect(name, 'Test User');
});
}A widget test passes the same overrides to ProviderScope:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('ProfilePage shows the repository name', (tester) async {
await tester.pumpWidget(
ProviderScope(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
child: const MaterialApp(home: ProfilePage(id: 1)),
),
);
await tester.pumpAndSettle();
expect(find.text('Test User'), findsOneWidget);
});
}Each test builds its own container, so state never leaks between tests. This is a real advantage over get_it, where a global registry must be reset in setUp and tearDown.
Lifetimes and scoping in brief
Riverpod handles lifetimes differently from get_it's three registration styles.
- A plain
Provideris created lazily on first read and then cached for the life of the container. That is closest to a lazy singleton. - Providers created with
autoDisposeare destroyed when nothing listens to them. They are closest to a factory whose instance is released automatically. - The
.familymodifier creates one cached instance per argument.
Nested ProviderScope widgets can also override providers for one subtree, which supports per-feature or per-session dependencies. The scoping chapter covers this in detail.
Common errors
Reading in build with ref.read. The widget builds once with the first value and never updates after an override or invalidation. Use ref.watch in build.
Calling ref.watch in a callback. Riverpod asserts against this. Use ref.read inside onPressed and similar handlers.
Overriding too late. Overrides apply when the container is created. If you read a provider before building a container with overrides, the real instance is already cached in a different container. In tests, always create the container with its overrides before the first read.
Forgetting to dispose a container. A container you create yourself, in tests or in main, holds provider state until you call dispose. ProviderScope does this for you.
Typing the provider with the concrete class. If you write Provider<ApiUserRepository>, an override must also be an ApiUserRepository, and a fake cannot qualify. Declare Provider<UserRepository>.
Mixed styles. Calling ProviderContainer().read(...) inside widgets creates a second container that ignores the overrides in ProviderScope. Read through ref in widgets.
Trade-offs
Riverpod gives you compile-time safety, easy overrides, and automatic rebuilds when dependencies change. In return, widgets and providers import Riverpod, so your code is tied to the package more than with plain constructor injection. Learning ref.watch versus ref.read, and the provider modifiers, takes time. If you only need a few shared services and no reactive rebuilds, Provider or get_it can be less machinery. If you want to override dependencies per test and per subtree without a global registry, Riverpod is a strong fit.
Exercise
A test overrides userRepositoryProvider with FakeUserRepository in a ProviderContainer, but the test still sees data from ApiUserRepository. The test code first calls ProviderContainer().read(userNameProvider(1).future) to warm up, then creates a second container with the override and reads again from that second container. The first read is also what produced the data being asserted. What went wrong, and how do you fix it?
Show answer
The warm-up read used a different container without the override, so it built and cached the real repository there. Overrides only apply to the container they are passed to, and each container has its own cache. Fix it by creating a single container with the overrides before any read, reading everything through that container, and disposing it with addTearDown.
Exercise
Why should a widget's build method call ref.watch(userRepositoryProvider) rather than ref.read(userRepositoryProvider), when the repository never changes in production?
Show answer
ref.watch subscribes the widget to the provider, so if the provider is overridden, invalidated, or rebuilt because one of its own dependencies changed, the widget rebuilds with the new value. ref.read returns the current value once and never notifies. Even if the value is stable in production, using watch in build is the safe default and costs almost nothing.