Sub topic 4
Wiring Everything in One Place
This chapter assumes you know Dart classes and abstract classes, Flutter widgets and BuildContext, Future and async/await, and basic ChangeNotifier state management.
What Is a Composition Root?
A composition root is the part of an application where concrete dependencies are created and connected. In a Flutter app, it is often near main() or the root widget.
For example, ProfileViewModel needs a UserRepository. The view model should not create ApiUserRepository itself. Instead, the composition root creates both objects and passes the repository to the view model.
This keeps object creation in one visible place:
| Part | Responsibility |
|---|---|
| `ApiUserRepository` | Fetch user data |
| `ProfileViewModel` | Coordinate data and notify the UI |
| Composition root | Create and connect objects |
| Widget tree | Make objects available to widgets |
When a backend changes, you can replace the repository in the composition root without editing the view model.
Wiring Dependencies with Provider
The following example uses the provider package. The first provider creates the repository. The second provider reads that repository and passes it to 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 {
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>(),
)..load(1),
),
],
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) {
return Scaffold(
appBar: AppBar(title: const Text('Profile')),
body: Center(
child: Consumer<ProfileViewModel>(
builder: (context, viewModel, child) {
return Text(viewModel.name ?? 'Loading...');
},
),
),
);
}
}MultiProvider builds a dependency chain from top to bottom. ProfileViewModel can read UserRepository because the repository provider appears before it.
context.read<T>() obtains a dependency without rebuilding the current widget when that dependency changes. The Consumer widget, in contrast, listens for ProfileViewModel notifications and rebuilds its child.
Keep the Root Deliberate
The composition root should be easy to find and should contain wiring, not business rules. Do not put API calls, validation, or screen-specific decisions there.
A common error is reversing provider order. A provider can only read another provider that exists above it in the widget tree. Another error is constructing the same repository separately for every screen, which can create inconsistent state.
The root is also a useful boundary for configuration. You can choose a production repository there, while tests can construct the same view model with a fake repository.
Exercise
Why should ProfileViewModel receive UserRepository from the composition root instead of constructing ApiUserRepository internally?
Show answer
The composition root controls the concrete implementation. The view model depends on the abstraction, so production, test, or local implementations can be supplied without changing the view model.