Sub topic 4
Wiring everything in one place
This chapter assumes you know Dart abstract classes and implements, Flutter's widget tree and BuildContext, async/await, and basic ChangeNotifier usage. It also assumes you have seen constructor injection and depending on abstractions. Here you will collect all object creation into one place, called the composition root.
What a composition root is
Constructor injection pushes the question "who creates this object?" up to the caller. If you never answer it, the question travels all the way up the call chain. Something must eventually write ApiUserRepository() and ProfileViewModel(repository).
The composition root is the single place in an app where you create the concrete objects and connect them. In a Flutter app this is usually main(), or a function that main() calls. Everything else in the app receives its dependencies from the outside and never builds them itself.
The rule has two halves:
- Only the composition root knows which concrete classes exist, such as
ApiUserRepository. - All other code names only the abstractions, such as
UserRepository.
This makes the composition root the one file you edit to change how the app is assembled. Swapping a real API for a mock server, or an in-memory cache for a database, becomes a change in one location.
The problem it fixes
Without a composition root, object creation scatters. A widget builds its own view model, which builds its own repository, which builds its own HTTP client:
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key});
@override
Widget build(BuildContext context) {
// Hard-coded: the screen decides which repository is used.
final viewModel = ProfileViewModel(ApiUserRepository());
return Text(viewModel.name ?? 'Loading');
}
}This code has three problems:
- The screen imports
ApiUserRepository, so it is coupled to a concrete class. - A new
ApiUserRepositoryis created on everybuild, which may run many times per second. - Two screens that need the same repository each create their own copy, so they cannot share a cache or a login token.
Moving creation to one place fixes all three.
A manual composition root
The simplest composition root uses no package. You build the objects in order, from the ones with no dependencies to the ones that need others:
import 'package:flutter/material.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => '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();
}
}
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key, required this.viewModel});
final ProfileViewModel viewModel;
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: viewModel,
builder: (context, _) => Text(viewModel.name ?? 'Loading'),
);
}
}
void main() {
// Composition root: the only place that names concrete classes.
final UserRepository repository = ApiUserRepository();
final viewModel = ProfileViewModel(repository)..load(1);
runApp(
MaterialApp(
home: Scaffold(body: Center(child: ProfileScreen(viewModel: viewModel))),
),
);
}main() is the only function that mentions ApiUserRepository. ProfileScreen and ProfileViewModel see only UserRepository and ProfileViewModel. Declaring repository with the type UserRepository makes that boundary visible.
Order matters
Dependencies form a graph. A view model needs a repository, and the repository may need an HTTP client. You must create them from the leaves of that graph inward.
void main() {
final httpClient = HttpClient(); // no dependencies
final repository = ApiUserRepository(httpClient); // needs httpClient
final viewModel = ProfileViewModel(repository); // needs repository
runApp(MyApp(viewModel: viewModel));
}If two objects depend on each other, there is no valid order. That is a circular dependency, and it signals a design problem. Usually a third class should own the shared behavior, or one side should receive a callback instead of the whole object.
Getting dependencies down the tree
Passing the view model through every widget constructor works for one screen. In a deep tree it becomes tedious. A widget in the middle of the tree has to accept and forward a dependency it never uses. This is called prop drilling.
The composition root does not have to hand objects to widgets one constructor at a time. It can place them into a structure that widgets read from. Flutter offers two common structures:
- The widget tree itself, using
InheritedWidgetor theproviderpackage. The next chapters cover this. - A global registry, using the service locator pattern and
get_it.
Either way, the composition root is still the one place that decides which objects exist. Here is the same wiring with provider:
void main() {
runApp(
MultiProvider(
providers: [
Provider<UserRepository>(create: (_) => ApiUserRepository()),
ChangeNotifierProvider<ProfileViewModel>(
create: (context) => ProfileViewModel(context.read<UserRepository>()),
),
],
child: const MyApp(),
),
);
}The providers list is the composition root. Providers earlier in the list can be read by providers later in the list, so order still matters. The create callbacks are lazy by default, so each object is built the first time something reads it.
Where the composition root should and should not live
Keep the composition root near the entry point. Good places include:
main()itself, for small apps.- A function such as
buildDependencies()called frommain(), for larger apps. - A root widget such as
App, when providers needBuildContext.
Avoid these placements:
- Inside a screen or widget deep in the tree. That hides object creation again.
- In a static global that any file can reach and modify without going through the root.
- Spread across several
main_*.dartfiles with copy-pasted wiring. Share the wiring and vary only the pieces that differ.
Multiple entry points and environments
A single composition root makes environments simple. Many apps have a production build, a development build pointing to a staging server, and a demo build with fake data. Each can be a separate entry point that calls shared wiring with different choices:
class AppDependencies {
AppDependencies({required this.userRepository});
final UserRepository userRepository;
}
AppDependencies buildProduction() =>
AppDependencies(userRepository: ApiUserRepository());
AppDependencies buildDemo() =>
AppDependencies(userRepository: DemoUserRepository());
class DemoUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Demo User';
}// lib/main_demo.dart
void main() {
final deps = buildDemo();
runApp(MyApp(deps: deps));
}You can run the demo build with flutter run -t lib/main_demo.dart. Nothing outside the composition root changed. This is the practical payoff of the pattern.
Common mistakes
- Creating objects inside
build.buildcan run on every rebuild, so you lose state and recreate resources such as HTTP clients. Create objects once, in the root or in a lazy provider. - Reaching back into the root. If a deep widget calls a global factory like
buildDependencies()itself, it has bypassed injection. Receive the dependency instead. - Putting logic in the root. The root should only create and connect objects. Reading preferences, branching on user data, or calling the network belongs elsewhere. A small amount of startup configuration is fine.
- Passing the whole container. Handing
AppDependenciesto every class lets each one pull whatever it likes. This hides what a class really needs, and it is the same weakness as a service locator. Pass only the specific dependencies a class uses. - Forgetting to dispose. The root creates objects that may hold resources, such as streams or database connections. Whoever creates an object is responsible for closing it. Provider's
createcallbacks disposeChangeNotifiers automatically. Objects you build by hand inmain()live for the whole app run, which is usually acceptable.
Asynchronous setup
Some dependencies need asynchronous setup, such as opening a database or reading stored settings. Do this before runApp, and make sure Flutter bindings are ready first:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final settings = await SettingsStore.open(); // async setup
final repository = ApiUserRepository();
runApp(MyApp(settings: settings, repository: repository));
}The advantage is that every class downstream receives a ready-to-use object and never has to check whether it has been initialized. The cost is a longer time before the first frame. If startup becomes slow, show a splash screen first and finish setup behind it, or defer non-essential dependencies.
Checking your work
A composition root is working when these statements hold:
| Check | Expected result |
|---|---|
| Which files import `ApiUserRepository`? | Only the composition root (and its own tests). |
| Where do you change the backend? | One file. |
| Can a view model be built in a test without Flutter? | Yes, by passing a fake to its constructor. |
| Does any widget call `SomeRepository()` directly? | No. |
Exercise
A teammate writes final repo = ApiUserRepository(); inside the build method of ProfileScreen, and says it is fine because the screen only uses the UserRepository interface afterward. Give two reasons this is still a problem, and say where the line should move.
Show answer
First, the screen imports and names the concrete ApiUserRepository, so it is still coupled to that implementation and tests cannot replace it. Second, build can run many times, so a new repository is created on each rebuild and any cache or token it holds is lost; separate screens also cannot share one instance. Move the creation to the composition root (for example main() or a Provider in the root's providers list) and have the screen receive a UserRepository through its constructor or through context.read<UserRepository>().
Exercise
In a composition root you write final viewModel = ProfileViewModel(repository); before final repository = ApiUserRepository(httpClient);. What happens, and what rule does the fix follow?
Show answer
Dart reports an error because repository is used before it is declared. The fix is to create objects from the leaves of the dependency graph inward: httpClient first, then repository, then viewModel.