Sub topic 5
Providing dependencies through the widget tree
This chapter assumes you know Dart abstract classes and implements, the Flutter widget tree and BuildContext, and the basics of ChangeNotifier. It also assumes you have seen constructor injection and a composition root from the earlier chapters.
Constructor injection works well for plain Dart classes. It gets tedious in a widget tree. If a ProfileScreen needs a UserRepository that a ProfileViewModel deep below it uses, every widget in between must accept and forward the repository, even though none of them use it. This chapter shows how Flutter solves that problem with InheritedWidget, and how the result is still dependency injection.
The problem: prop drilling
Consider a tree where App creates a repository and a leaf widget needs it:
class App extends StatelessWidget {
const App({super.key, required this.repository});
final UserRepository repository;
@override
Widget build(BuildContext context) {
return MaterialApp(home: HomePage(repository: repository));
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key, required this.repository});
final UserRepository repository;
@override
Widget build(BuildContext context) {
return Scaffold(body: ProfileCard(repository: repository));
}
}HomePage never calls the repository. It only forwards it. This is called prop drilling. Each new dependency adds a parameter to every widget on the path, and moving a widget to a different place in the tree means rewiring its ancestors.
The widget tree as a dependency container
Flutter already has a mechanism for passing data down the tree without passing it through constructors: InheritedWidget. An inherited widget sits at some point in the tree. Any descendant can ask for it through its BuildContext, and Flutter finds the nearest ancestor of that type.
Here is a minimal hand-written version that exposes a UserRepository:
import 'package:flutter/widgets.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class RepositoryScope extends InheritedWidget {
const RepositoryScope({
super.key,
required this.repository,
required super.child,
});
final UserRepository repository;
static UserRepository of(BuildContext context) {
final scope =
context.getInheritedWidgetOfExactType<RepositoryScope>();
assert(scope != null, 'No RepositoryScope found in context');
return scope!.repository;
}
@override
bool updateShouldNotify(RepositoryScope oldWidget) =>
repository != oldWidget.repository;
}A descendant calls RepositoryScope.of(context) and gets the repository, with no intermediate widget involved. The lookup walks up the tree from the calling context to the nearest RepositoryScope.
Three details matter:
ofreturns the abstract type. Descendants never learn which implementation they received, so the abstraction rule from the previous chapter still holds.getInheritedWidgetOfExactTypereads the value without registering a rebuild.dependOnInheritedWidgetOfExactTypealso subscribes the calling widget, so it rebuilds whenupdateShouldNotifyreturns true. For a stable dependency such as a repository, you usually do not want a subscription.- The
assertturns a missing ancestor into an immediate, readable error in debug mode.
Why this is still dependency injection
The widget does not create its repository. Something outside it supplies the repository, and the widget depends on an abstraction. The difference from constructor injection is the delivery route. A constructor passes the object explicitly. The widget tree delivers it implicitly, using the position of the widget as the key.
That implicitness has a cost. A constructor shows every dependency in its signature. A lookup through context hides them. If you forget to place the scope above a widget, the compiler cannot warn you. You find out at runtime.
Dependency injection with Provider
Writing an InheritedWidget for every dependency is repetitive. The provider package wraps the pattern into a few reusable widgets. Add it to pubspec.yaml:
dependencies:
flutter:
sdk: flutter
provider: ^6.1.0The main pieces are:
| Widget or method | Purpose |
|---|---|
| `Provider<T>` | Exposes a value of type `T` that never notifies listeners |
| `ChangeNotifierProvider<T>` | Exposes a `ChangeNotifier` and rebuilds listeners when it calls `notifyListeners` |
| `MultiProvider` | Lists several providers without deep nesting |
| `context.read<T>()` | Gets the value once, without subscribing to changes |
| `context.watch<T>()` | Gets the value and rebuilds the widget when it changes |
| `context.select<T, R>()` | Rebuilds only when a selected part of the value changes |
The composition root with Provider
The widget tree becomes the composition root. All wiring sits in main():
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.watch<ProfileViewModel>().name;
return Scaffold(
body: Center(child: Text(name ?? 'Loading...')),
);
}
}Look at how the pieces connect:
Provider<UserRepository>declares the type as the abstract class. Consumers ask forUserRepository, notApiUserRepository.- Providers in a list are created in order, and a later provider can read an earlier one.
ProfileViewModelreceives the repository through its own constructor, so it is still plain constructor injection. Provider only moves the object to where it is needed. createruns lazily by default. The view model is built the first time something reads it.ChangeNotifierProviderdisposes the view model when it leaves the tree.Providercalls the optionaldisposecallback you pass.
`read`, `watch`, and where to call them
Calling the wrong method is the most common Provider error.
- Use
context.watchorcontext.selectinsidebuild. They subscribe the widget to changes. - Use
context.readin callbacks such asonPressed, and ininitState. Callingreadinbuildworks but misses updates. CallingwatchininitStateor in a callback throws an error, because there is no build to schedule. - In a
createcallback, usecontext.read, as in the example above. Usingwatchthere would rebuild the object when the dependency changes, which is rarely what you want for a view model.
Common errors
ProviderNotFoundException. The widget asked for a type that no ancestor provides. Typical causes are:
- The provider sits in a different branch of the tree. Routes pushed with
Navigatorare children of theNavigator, which is belowMaterialApp. A provider placed inside one screen is not visible to another route. - The type does not match. Providing
Provider<ApiUserRepository>and readingcontext.read<UserRepository>()fails, because Provider matches the exact generic type. Always write the type argument explicitly. - The code uses the same
BuildContextthat creates the provider. A context only sees ancestors, so a widget that creates aProviderin itsbuildmethod cannot read it through that samecontext. Wrap the consumer in aBuilderor move it into a child widget.
Forgetting the type argument. Writing Provider(create: (_) => ApiUserRepository()) infers ApiUserRepository. The lookup for UserRepository then fails at runtime.
Using Provider.value for new objects. Provider.value(value: ApiUserRepository()) inside a build method creates a new object on every rebuild. Use create when the provider owns the object, and .value only to expose an object that already exists.
Placing providers in the tree
Where you put a provider decides its scope. A provider above MaterialApp is visible to every route, and lives as long as the app. A provider placed above a single screen exists only while that screen is in the tree. For shared services, such as repositories, put them at the top. For per-screen view models, put them next to the screen. A later chapter returns to this idea as scoping.
Trade-offs of using the widget tree
| Strength | Limitation |
|---|---|
| No extra package for the basic form, since `InheritedWidget` ships with Flutter | Lookups need a `BuildContext`, so non-widget code cannot resolve dependencies directly |
| Dependency scope follows the tree, and disposal is automatic | A missing provider is a runtime error, not a compile error |
| Overriding a dependency for a subtree is a matter of adding a provider below | Dependencies are hidden inside widget bodies rather than shown in signatures |
The context requirement is the main limit. A background service or a plain Dart class that runs outside the widget tree cannot call context.read. Such code receives its dependencies through constructors, supplied during wiring. For code that truly needs lookup without a context, the next chapters introduce the service locator pattern.
Exercise
A widget calls context.read<UserRepository>() and throws ProviderNotFoundException, although main() declares Provider<ApiUserRepository>(create: (_) => ApiUserRepository()). What is wrong, and how do you fix it?
Show answer
Provider matches the exact generic type. The provider exposes ApiUserRepository, but the widget asks for UserRepository. Change the declaration to Provider<UserRepository>(create: (_) => ApiUserRepository()), so the abstract type is the one registered.
Exercise
In a ProfilePage widget, where should you call context.watch<ProfileViewModel>(), and where should you call context.read<ProfileViewModel>() to trigger load? Give a reason for each.
Show answer
Call watch inside build, because it subscribes the widget so it rebuilds when notifyListeners runs. Call read in initState or in a callback such as onPressed, because those places run outside a build and should not subscribe. watch in those places throws an error.
Exercise
Why does ProfileViewModel take its repository in the constructor instead of calling context.read itself?
Show answer
The view model stays a plain Dart class with no dependency on Flutter or Provider. A unit test can build it with ProfileViewModel(FakeUserRepository()) without any widget tree, and the dependency stays visible in the constructor signature.