Sub topic 6
Dependency Injection with Provider
Assume you know Dart classes, BuildContext, widget trees, Future, and ChangeNotifier. In this chapter, you will use the provider package to pass dependencies through Flutter's widget tree.
Why use Provider?
A dependency is an object that another object needs to do its work. For example, a view model may need a repository to load user data. Passing that repository through constructors is explicit, but passing it through many widget constructors can become repetitive.
Provider stores an object above the widgets that need it. Descendant widgets can then retrieve the object from BuildContext.
Provider uses Flutter's InheritedWidget mechanism internally. The package adds convenient APIs for creating, reading, and listening to objects.
| API | Purpose |
|---|---|
| `context.read<T>()` | Get `T` once without rebuilding |
| `context.watch<T>()` | Get `T` and rebuild when it changes |
| `context.select<T, R>()` | Listen to one selected value |
| `Provider<T>` | Supply an ordinary object |
| `ChangeNotifierProvider<T>` | Supply a `ChangeNotifier` |
Create a provider hierarchy
Add provider to pubspec.yaml, then place providers above the widgets that use them. This location is often called the composition root because it is where the application wires its objects together.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async {
return 'User $id';
}
}
class ProfileViewModel extends ChangeNotifier {
ProfileViewModel(this._repository);
final UserRepository _repository;
String? name;
bool loading = false;
Future<void> load() async {
loading = true;
notifyListeners();
name = await _repository.fetchName(1);
loading = false;
notifyListeners();
}
}
void main() {
runApp(
MultiProvider(
providers: [
Provider<UserRepository>(
create: (_) => ApiUserRepository(),
),
ChangeNotifierProvider<ProfileViewModel>(
create: (context) => ProfileViewModel(
context.read<UserRepository>(),
),
),
],
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: ProfilePage());
}
}
class ProfilePage extends StatelessWidget {
const ProfilePage({super.key});
@override
Widget build(BuildContext context) {
final viewModel = context.watch<ProfileViewModel>();
return Scaffold(
appBar: AppBar(title: const Text('Profile')),
body: Center(
child: viewModel.loading
? const CircularProgressIndicator()
: Text(viewModel.name ?? 'No name loaded'),
),
floatingActionButton: FloatingActionButton(
onPressed: () => context.read<ProfileViewModel>().load(),
child: const Icon(Icons.download),
),
);
}
}context.watch makes ProfilePage rebuild when ProfileViewModel calls notifyListeners. The button uses context.read because triggering load does not require a separate rebuild at that line.
Ownership and common errors
The provider that creates an object owns that object. ChangeNotifierProvider disposes a notifier created with its create callback when the provider leaves the tree. Do not reuse the same notifier in multiple places unless you understand its lifecycle.
A frequent error is reading a provider above its position in the tree. A widget can read only providers in its ancestor path. Another error is using watch for an event handler and causing unnecessary rebuilds. Use read for commands and watch or select for displayed state.
Exercise
Which lookup should a widget use to display a view model's changing name, and which lookup should a button use to call load?
Show answer
Use context.watch<ProfileViewModel>() for the displayed name and context.read<ProfileViewModel>() in the button callback.