Sub topic 5
Providing Dependencies Through the Widget Tree
This chapter assumes you know Dart classes, BuildContext, widget trees, Future, async and await, and basic ChangeNotifier state management. You will use those ideas to provide objects to widgets without constructing them inside each widget.
How the widget tree supplies dependencies
Flutter widgets form a tree. An InheritedWidget is a widget designed to make a value available to its descendants. A descendant can find that value through its BuildContext.
Dependency injection uses this behavior to pass services, repositories, and view models down the tree:
The widget that creates an object owns its lifetime. When that widget leaves the tree, Flutter can dispose of objects created by providers that support disposal.
Using the Provider package
The provider package offers convenient widgets around InheritedWidget. The most common widgets are:
Provider<T>supplies an object that does not notify widgets about changes.ChangeNotifierProvider<T>supplies aChangeNotifierand rebuilds listeners afternotifyListeners().context.read<T>()gets a value without subscribing to changes.context.watch<T>()gets a value and rebuilds the widget when that value changes.
First, define an abstraction for the dependency and inject it into the view model:
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 {
await Future<void>.delayed(const Duration(milliseconds: 300));
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 MaterialApp(
home: ProfileScreen(),
),
),
);
}
class ProfileScreen extends StatelessWidget {
const ProfileScreen({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.refresh),
),
);
}
}MultiProvider is a convenience widget that nests several providers. The repository provider appears first, so the view model provider can read it while creating ProfileViewModel.
The screen uses watch when displaying state. It uses read inside the button callback because the callback needs to call a method, not rebuild when the view model changes.
Common errors
Do not create a provider inside a widget that needs the same provider. That widget is above the provider and cannot read it. Move the provider higher in the tree.
Do not use watch for every lookup. Watching creates a rebuild subscription. Use read for one-time access, such as event handlers, and watch for values rendered by the widget.
When one dependency needs another, place the required dependency earlier in MultiProvider. This makes the construction order clear and keeps wiring in the application's composition root.
Exercise
Which lookup should a button use when it only needs to call a view model method, read or watch?
Show answer
Use context.read<T>(). The button does not need to rebuild when the view model changes.