Sub topic 2
Passing dependencies through constructors
This chapter assumes you know Dart classes, abstract classes and implements, async/await, and the basics of a ChangeNotifier-style view model. You do not need to know Provider or get_it yet. Here we use plain Dart only.
The idea in one sentence
Constructor injection means a class declares what it needs as constructor parameters, and the code that creates the object supplies those values. The class never creates or looks up its collaborators itself.
Compare two versions of the same view model.
import 'package:flutter/foundation.dart';
class ApiUserRepository {
Future<String> fetchName(int id) async {
// Call the real backend here.
return 'User $id';
}
}
// Hard-coded dependency: the view model builds its own repository.
class HardCodedProfileViewModel extends ChangeNotifier {
final ApiUserRepository _repository = ApiUserRepository();
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
notifyListeners();
}
}
// Constructor injection: the caller decides which repository to use.
class ProfileViewModel extends ChangeNotifier {
ProfileViewModel(this._repository);
final ApiUserRepository _repository;
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
notifyListeners();
}
}The two classes have the same behavior at runtime. The difference is who makes the decision. In the first class, HardCodedProfileViewModel is permanently tied to ApiUserRepository. In the second, ProfileViewModel only says "give me a repository", and any caller can answer.
Why constructors are the right place
Dart offers several ways to hand a dependency to an object: constructor parameters, setters or public fields, and method parameters. Constructors are usually the best default for these reasons.
- Required dependencies are enforced by the compiler. If a parameter is
requiredor positional and non-nullable, you cannot create the object without it. A missing dependency becomes a compile error instead of anullcrash at runtime. - The object is always fully built. There is no window between
newand "setup" where the object is half-initialized. - Dependencies can be
final. The object cannot have a collaborator swapped out from under it later. - The class signature documents its needs. Reading the constructor tells you what the class talks to.
The last point is a useful design signal. If a constructor grows to seven or eight parameters, the class probably has too many responsibilities. Constructor injection makes that smell visible, whereas hidden dependencies (such as global variables or singletons) hide it.
Writing the constructor in idiomatic Dart
Dart has a shorthand that keeps injection compact. The this._repository form is an initializing formal parameter. It assigns the argument directly to the field.
class ProfileViewModel extends ChangeNotifier {
ProfileViewModel(this._repository);
final UserRepository _repository;
}A private field name such as _repository is fine with positional parameters, because the parameter name is not exposed. If you use named parameters, Dart does not allow a private name there, so you need a public parameter name and an initializer list.
class ProfileViewModel extends ChangeNotifier {
ProfileViewModel({
required UserRepository repository,
required Analytics analytics,
}) : _repository = repository,
_analytics = analytics;
final UserRepository _repository;
final Analytics _analytics;
}Use positional parameters when there are one or two dependencies. Switch to named required parameters when there are three or more, so call sites stay readable and arguments cannot be swapped by accident when two parameters share a type.
A complete, runnable example
The next program shows the whole flow without Flutter widgets. It uses only dart:async, so you can run it with dart run. The view model is a plain class with a callback in place of ChangeNotifier, so the file has no Flutter dependency.
class UserRepository {
Future<String> fetchName(int id) async => 'User $id';
}
class Greeter {
Greeter(this._repository);
final UserRepository _repository;
Future<String> greet(int id) async {
final name = await _repository.fetchName(id);
return 'Hello, $name!';
}
}
Future<void> main() async {
// The caller creates the dependency and hands it in.
final repository = UserRepository();
final greeter = Greeter(repository);
print(await greeter.greet(7)); // Hello, User 7!
}Notice that main() is the only place that uses UserRepository() with new-style construction. Greeter never does. That separation is the core of the pattern.
What the dependency graph looks like
Real apps have chains of dependencies. A view model needs a repository, the repository needs an HTTP client, and the client needs a base URL. Constructor injection makes each link explicit, and the objects must be built from the bottom up.
Each arrow means "is passed into the constructor of". You create HttpClient first, then UserRepository, then ProfileViewModel. Writing this by hand is easy for a few classes. The later chapters on the composition root, Provider, and get_it show how to avoid repeating this wiring in many places.
Injecting into widgets
Widgets are classes too, so they can receive dependencies through their constructors.
import 'package:flutter/material.dart';
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...'),
);
}
}This works, and it is useful for small leaf widgets and for widget tests where you pass in a prepared object. It becomes painful when a dependency is needed deep in the tree, because every widget in between must accept and forward it.
Edge cases and common mistakes
Prop drilling
If AppRoot needs a repository only so it can pass it to HomePage, which passes it to ProfileTab, which passes it to ProfileScreen, the intermediate widgets carry parameters they never use. This is called prop drilling. It is the main reason Flutter apps move to the widget tree (InheritedWidget, Provider) for widget-level dependencies. Constructor injection remains the right tool for non-widget classes such as view models and repositories.
Creating the dependency inside the constructor body
This looks like injection but is not.
class ProfileViewModel extends ChangeNotifier {
// Still hard-coded: callers cannot change this.
ProfileViewModel() : _repository = ApiUserRepository();
final UserRepository _repository;
}The field type is abstract, but the class still chooses the implementation. A test cannot replace it. A related pattern is an optional parameter with a default, which is acceptable in small cases.
ProfileViewModel([UserRepository? repository])
: _repository = repository ?? ApiUserRepository();This keeps the call site short and still allows a test to pass a fake. The cost is that the class now imports and knows about ApiUserRepository, so the coupling remains in the source. Prefer a required parameter once the app has a place that wires everything together.
Reading a global from inside the class
Calling GetIt.instance<UserRepository>() or reading a static Repository.instance inside a method is not constructor injection. The dependency is invisible in the signature. We cover this approach, the service locator, in a later chapter and explain when it is acceptable.
Circular dependencies
If A needs B in its constructor and B needs A, neither can be built first. Dart will not stop you from writing this, but you cannot construct the objects without a workaround such as a late-assigned field. Treat the cycle as a design problem. Usually a third class holds the shared logic, or one side should receive a callback instead of the whole object.
Injecting too much
Pass the narrowest thing a class needs. A view model that only reads a user's name should receive a UserRepository, not the whole AppServices bag that holds twenty services. A broad parameter hides what the class really uses and makes tests harder to set up.
Injecting values that change over time
A constructor runs once. If the dependency can change (for example, a repository tied to the signed-in user), a long-lived object holding the old one will use stale data. Either create a new object when the dependency changes, or inject a provider-style function that returns the current value. Later chapters on lifetimes and scoping cover this in detail.
Lifetime follows from who creates the object
With constructor injection, the creator controls how long each dependency lives. If main() creates one UserRepository and passes it to three view models, they share it. If each view model gets its own instance, they do not. The class itself does not care.
| Choice at the call site | Result |
|---|---|
| Create once, pass to many | Shared state, such as one cache or one HTTP connection pool |
| Create per consumer | Isolated state, more memory |
| Create per screen visit | Fresh state each time, disposed with the screen |
If an injected object needs cleanup (closing a stream, for example), decide who owns it. A common rule is that whoever creates an object disposes of it. A view model that receives a repository should not close it, because other classes may still use it.
Quick checklist
- Does the class declare every collaborator it uses as a constructor parameter?
- Are the fields
final? - Does the class avoid calling
ApiX()or reading a global for those collaborators? - Is the parameter list short enough to read at a glance?
- Is it clear who creates and who disposes each dependency?
Exercise
In the class below, name the problem that prevents a unit test from using a fake, and rewrite the constructor so the test can supply its own repository. class CartViewModel { CartViewModel() : repository = ApiCartRepository(); final CartRepository repository; }
Show answer
The constructor builds ApiCartRepository itself, so the class decides the implementation and callers cannot change it, even though the field type is abstract. Accept the dependency as a parameter instead: CartViewModel(this.repository); with final CartRepository repository;. A test can then call CartViewModel(FakeCartRepository()).
Exercise
A ProfileViewModel is given a UserRepository through its constructor and also owns a StreamSubscription it opened itself. Which of the two should its dispose method clean up, and why?
Show answer
It should cancel the StreamSubscription, because the view model created it. It should not dispose of the UserRepository, because the creator of the repository owns it and other classes may still be using the same instance.