Sub topic 11
Dependency injection with Riverpod
This chapter assumes you know Dart classes, abstract classes, Future, async/await, Flutter widgets, and basic state-management ideas such as ChangeNotifier.
Riverpod uses providers as declarations for dependencies and state. A provider describes how to create a value. A ProviderScope stores the values, and a Ref lets one provider read another. This keeps dependency wiring explicit without requiring a BuildContext.
Define a repository provider
Start with an abstraction. The rest of the app depends on UserRepository, not on a specific HTTP client.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async {
await Future<void>.delayed(const Duration(milliseconds: 300));
return 'User $id';
}
}
final userRepositoryProvider = Provider<UserRepository>(
(ref) => ApiUserRepository(),
);
final userNameProvider = FutureProvider.family<String, int>(
(ref, id) {
final repository = ref.watch(userRepositoryProvider);
return repository.fetchName(id);
},
);
class UserNamePage extends ConsumerWidget {
const UserNamePage({super.key, required this.userId});
final int userId;
@override
Widget build(BuildContext context, WidgetRef ref) {
final name = ref.watch(userNameProvider(userId));
return Scaffold(
appBar: AppBar(title: const Text('Profile')),
body: Center(
child: name.when(
loading: () => const CircularProgressIndicator(),
error: (error, stackTrace) => Text('Error: $error'),
data: (value) => Text(value),
),
),
);
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: UserNamePage(userId: 1),
);
}
}
void main() {
runApp(
const ProviderScope(
child: MyApp(),
),
);
}userRepositoryProvider supplies one repository implementation. The family provider accepts an id and calls ref.watch to obtain the repository. ref.watch also tells Riverpod to recalculate the provider if the watched dependency changes.
FutureProvider represents an asynchronous value. Its result is an AsyncValue, which has loading, error, and data states. The widget handles all three states instead of reading a possibly incomplete field.
Override dependencies in tests
A provider's default creation function is used in production. A test can replace it with an override. The code that reads the provider does not need to change.
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Test User';
}
void main() async {
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(
FakeUserRepository(),
),
],
);
final name = await container.read(userNameProvider(1).future);
print(name); // Test User
container.dispose();
}ProviderContainer is the non-UI equivalent of ProviderScope. It is useful in unit tests because it can resolve providers without starting Flutter widgets. In a Flutter test, place the widget under ProviderScope and pass the same override.
Watching, reading, and scoping
Use ref.watch when a widget or provider should react to changes. Use ref.read for a one-time lookup, such as starting an action from a button callback. Reading instead of watching prevents a widget from rebuilding, but using read everywhere can hide needed updates.
You can nest ProviderScope widgets to limit an override to one feature, route, or user session. This is useful when two parts of an application need different repositories or session data.
Choosing Riverpod for dependency injection
Riverpod works well when dependencies and application state are closely connected. It provides reactive updates, asynchronous states, provider overrides, and scoping without passing BuildContext through non-widget code.
A service locator can be simpler for a small collection of app-wide services. Provider-based wiring makes dependencies visible in the provider graph, while a locator hides lookups behind global calls. Choose Riverpod when explicit graphs, overrides, and reactive state matter more than minimal setup.
Exercise
How would you test userNameProvider without making a network request?
Show answer
Create a ProviderContainer with an override for userRepositoryProvider, supply a fake repository, then read userNameProvider(id).future.