Sub topic 6
Dependency injection with Provider
This chapter assumes you know Dart abstract classes, BuildContext, and the widget tree. It also assumes you have used ChangeNotifier and understand constructor injection and a composition root from the earlier chapters. The provider package is the usual way to put that composition root inside a Flutter app.
What Provider adds
Provider is a thin wrapper around InheritedWidget. You place a provider widget high in the tree, and any descendant can look up the object it holds through BuildContext. This gives you three things that plain constructor injection does not:
- You do not pass a repository through every intermediate widget.
- The package creates objects when they are first needed and can dispose of them when the provider leaves the tree.
- Widgets can rebuild automatically when a
ChangeNotifierchanges.
Provider is not a service locator, even though context.read looks like a lookup. The lookup is tied to a position in the tree, so two subtrees can hold different instances of the same type.
The two layers: repositories and view models
A typical app has two kinds of provided objects.
| Object | Provider widget | Changes over time? | Typical lifetime |
|---|---|---|---|
| Repository, API client, service | `Provider<T>` | No | App or session |
| View model (`ChangeNotifier`) | `ChangeNotifierProvider<T>` | Yes | App, screen, or feature |
The view model depends on the repository, and the repository is registered first. This is the same code as in the spine, with the imports and the UI added so it runs.
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 {
// Call the real backend here.
return 'User $id';
}
}
class ProfileViewModel extends ChangeNotifier {
ProfileViewModel(this._repository);
final UserRepository _repository;
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
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 StatefulWidget {
const ProfilePage({super.key});
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
@override
void initState() {
super.initState();
context.read<ProfileViewModel>().load(1);
}
@override
Widget build(BuildContext context) {
final name = context.select((ProfileViewModel vm) => vm.name);
return Scaffold(
body: Center(child: Text(name ?? 'Loading...')),
);
}
}MultiProvider is only a flat way of writing nested providers. The first entry becomes the outermost widget. That is why UserRepository must come before ProfileViewModel: the second create callback looks upward in the tree, and only providers above it are visible.
read, watch, and select
Provider adds three methods to BuildContext. Choosing the wrong one is the most common source of bugs.
| Method | Listens for changes? | Use it in |
|---|---|---|
| `context.read<T>()` | No | `initState`, callbacks, `create` functions |
| `context.watch<T>()` | Yes, rebuilds on any notification | `build` only |
| `context.select<T, R>(f)` | Yes, rebuilds only when `f` returns a different value | `build` only |
For dependency injection the rule is simple. When you only want to obtain a dependency, such as a repository or a view model whose methods you will call, use read. When you want to display state, use watch or select in build.
Dependencies that depend on other dependencies
Reading with context.read inside create works when the dependency never changes. If a dependency can be replaced, for example an API client that gets a new token after login, use a proxy provider. It rebuilds the dependent object when its input changes.
import 'package:provider/provider.dart';
class AuthState {
AuthState(this.token);
final String? token;
}
class ApiClient {
ApiClient(this.token);
final String? token;
}
abstract class OrderRepository {
Future<int> countOrders();
}
class ApiOrderRepository implements OrderRepository {
ApiOrderRepository(this._client);
final ApiClient _client;
@override
Future<int> countOrders() async => _client.token == null ? 0 : 3;
}
final providers = [
Provider<AuthState>(create: (_) => AuthState(null)),
ProxyProvider<AuthState, ApiClient>(
update: (_, auth, __) => ApiClient(auth.token),
),
ProxyProvider<ApiClient, OrderRepository>(
update: (_, client, __) => ApiOrderRepository(client),
),
];Use providers as the providers list of a MultiProvider. ProxyProvider<A, B> reads A from above and builds a B. The third argument of update is the previous value, which you can reuse or dispose. For a view model, use ChangeNotifierProxyProvider, which keeps the same notifier instance across updates if you return the previous one.
The generic type is the key
Provider finds objects by their type argument, not by the runtime type of the object. This produces the most frequent surprise in DI with Provider.
// Registers a Provider<ApiUserRepository>. Dart infers the type from create.
Provider(create: (_) => ApiUserRepository());
// Registers a Provider<UserRepository>. This is the one you want.
Provider<UserRepository>(create: (_) => ApiUserRepository());With the first form, context.read<UserRepository>() fails with a ProviderNotFoundException, because no Provider<UserRepository> exists above the widget. Always write the abstract type explicitly. It is also what makes the replacement in tests possible.
Lifetimes and disposal
Provider's behavior maps to the lifetimes you will meet again with get_it:
createis lazy by default. The object is built the first time something reads it. Passlazy: falsefor objects that must start at launch, such as a listener on a stream.- The object lives as long as its provider widget stays in the tree. If you place a provider around one route, a new instance is created each time that route is pushed.
ChangeNotifierProvidercallsdisposeon the notifier when it leaves the tree.Provideraccepts adisposecallback for closing streams, database handles, and similar resources.Provider.valueandChangeNotifierProvider.valuedo not dispose the object. Use them when something else owns the instance, which is the right choice in tests and when passing an existing object to a new route.
A common mistake is writing ChangeNotifierProvider(create: (_) => existingNotifier). Provider then disposes a notifier it did not create. Use .value for existing instances.
Testing with Provider
Because widgets obtain dependencies through the tree, a test replaces them by wrapping the widget under test with different providers. No production code changes. The fake class is the same one you would use in a plain unit test.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Test User';
}
void main() {
testWidgets('ProfilePage shows the name from the repository', (tester) async {
await tester.pumpWidget(
MultiProvider(
providers: [
Provider<UserRepository>.value(value: FakeUserRepository()),
ChangeNotifierProvider<ProfileViewModel>(
create: (context) =>
ProfileViewModel(context.read<UserRepository>()),
),
],
child: const MaterialApp(home: ProfilePage()),
),
);
expect(find.text('Loading...'), findsOneWidget);
await tester.pumpAndSettle();
expect(find.text('Test User'), findsOneWidget);
});
}The test duplicates the wiring from main. To avoid drifting apart, move the provider list into a function such as List<SingleChildWidget> buildProviders() that takes optional overrides, and call it from both places. If you only need to test the view model, skip Provider and pass the fake to the constructor directly.
Common errors
ProviderNotFoundException. Either the type argument does not match (see above), or the widget'sBuildContextsits above the provider. The second case happens when you callcontext.readin the samebuildmethod that creates the provider. Wrap the child in aBuilder, or move it into its own widget, so it gets a context below the provider.- Provider order. A
createthat reads a type registered later in the list fails, because that provider is not yet an ancestor. - Reading across routes. A provider created inside one route is not visible to a route pushed from it. Place the provider above
MaterialApp, or pass the value to the new route with a.valueprovider. - Over-rebuilding. Calling
watchon a view model with many fields rebuilds the widget for any change. Useselector split the widget. - Dependencies hidden in
build. Reading a repository directly in many widgets recreates the coupling DI was meant to remove. Let view models read repositories, and let widgets read view models.
Exercise
A teammate writes Provider(create: (_) => ApiUserRepository()) in main, and a view model's create calls context.read<UserRepository>(). The app crashes with a ProviderNotFoundException. Why does it fail, how do you fix it, and what does the fix allow in tests?
Show answer
Dart infers the provider's type from the create return value, so the code registers a Provider<ApiUserRepository>. The lookup asks for Provider<UserRepository>, which does not exist in the tree. Fix it by writing Provider<UserRepository>(create: (_) => ApiUserRepository()). The tree now exposes the abstract type, so a test can supply Provider<UserRepository>.value(value: FakeUserRepository()) and the view model receives the fake without any change to production code.