Sub topic 1
What dependency injection solves
Dependency injection (DI) means a class receives the objects it needs from outside instead of creating them itself. This chapter shows the problem DI addresses, the smallest change that fixes it, and the mistakes people make when they first apply it. Later chapters cover the mechanisms in detail: constructors, Provider, get_it, and Riverpod.
Prerequisites
This chapter assumes you already know:
- Dart classes, abstract classes, and
implements. - Flutter widgets,
BuildContext, and the widget tree. - Futures and
async/await. - The basic idea of
ChangeNotifieras a holder of UI state.
You don't need any DI package yet. Everything here uses plain Dart.
What a dependency is
A dependency is any object a class needs in order to do its work. If ProfileViewModel calls a repository to load a user's name, the repository is a dependency of the view model. A class's dependencies usually include:
- Repositories and API clients.
- Local storage, such as a database or
SharedPreferences. - Clocks, random number generators, and loggers.
- Platform services such as location or notifications.
Having dependencies is normal. The question is who creates them and who decides which implementation is used.
The problem: hard-coded dependencies
Here is a view model that creates its own repository:
import 'package:flutter/foundation.dart';
class ApiUserRepository {
Future<String> fetchName(int id) async {
// Imagine a real HTTP call here.
await Future<void>.delayed(const Duration(milliseconds: 300));
return 'User $id';
}
}
class ProfileViewModel extends ChangeNotifier {
final ApiUserRepository _repository = ApiUserRepository();
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
notifyListeners();
}
}This works, but the line ApiUserRepository() fixes a decision inside the class. That causes three concrete problems.
- Testing needs the real backend. A test of
ProfileViewModelcalls the realApiUserRepository. The test is slow, depends on the network, and can fail for reasons unrelated to the view model. - Changes spread. Suppose you replace the repository with a cached version, or give it a constructor parameter such as a base URL. Every class that writes
ApiUserRepository()must be edited. - Hidden requirements. The constructor
ProfileViewModel()looks like it needs nothing. In fact it needs a working network stack. A reader can't see that from the signature.
The underlying issue is coupling. Coupling means one piece of code knows about and relies on a specific other piece. Here ProfileViewModel is coupled to one concrete class, and it also controls that class's creation.
The fix: receive, don't create
Move the creation outside the class and receive the object through the constructor:
import 'package:flutter/foundation.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();
}
}Two changes were made, and they do different jobs:
- Injection.
ProfileViewModeltakes its repository as a constructor parameter. Whoever builds the view model chooses the repository. - Abstraction. The field type is
UserRepository, an abstract class, notApiUserRepository. The view model now depends only on what a repository can do (fetchName), not on how it does it.
Injection without abstraction still helps, because the caller controls creation. Abstraction is what lets you substitute a different implementation. Chapters 2 and 3 treat each in turn.
Now the test needs no network:
import 'package:flutter_test/flutter_test.dart';
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Test User';
}
void main() {
test('load stores the name from the repository', () async {
final viewModel = ProfileViewModel(FakeUserRepository());
await viewModel.load(1);
expect(viewModel.name, 'Test User');
});
}The test is fast and deterministic. It also checks only the view model's logic.
Direction of control
DI changes who is in charge of construction. The following diagram compares the two designs.
The code that creates and connects objects is called the composition root. In an app it is usually main(). In a test it is the test body. Chapter 4 covers it properly. For now, note that "who creates this object?" has one clear answer, and that answer is not the class that uses it.
Dependency injection is not a framework
DI is a design practice. The code above uses no package. Tools such as Provider, get_it, and Riverpod help you deliver objects to the places that need them, but each one is optional. The comparison below shows where each tool fits in later chapters.
| Idea | What it is | Needs a package? |
|---|---|---|
| Constructor injection | Pass dependencies as constructor arguments | No |
| Widget-tree injection | Place objects above widgets and read them through `BuildContext` | Provider, or plain `InheritedWidget` |
| Service locator | A global registry you ask for objects | get_it |
| Provider graph | Declared providers that can be overridden | Riverpod |
Manual constructor injection scales further than most people expect. A package becomes useful when passing the same object through many layers gets tedious, or when you need controlled lifetimes.
Why it matters in Flutter specifically
Flutter apps have several features that make hard-coded dependencies costly.
- Widgets are rebuilt often. If a widget creates a dependency inside
build, it creates a new one on every rebuild. That can silently discard cached data or open duplicate connections. - Widget tests run without a real platform. Plugins such as storage and location usually throw or hang in tests unless you substitute them.
- Apps have several environments. Development, staging, and production often need different backends. Injection lets you change the wiring without editing business logic.
- State holders are layered. Widgets use view models, which use repositories, which use data sources. Each layer is a place where a hard-coded
newcould pin the whole chain to one implementation.
Common mistakes
These are the errors intermediate developers make most often when starting with DI.
- Creating the dependency in
build. WritingProfileViewModel(ApiUserRepository())insidebuildmakes a new pair on every rebuild. Create objects once, in the composition root or in a provider'screatecallback. - Injecting the concrete type. If the field is
ApiUserRepository, you can pass a subclass but you can't cleanly pass an unrelated fake. Declare the abstract type. - Abstracting everything. Not every class needs an interface. Abstract the boundaries that you want to replace: network, storage, time, and platform services. Pure helper functions and simple value classes can stay concrete.
- Using a constructor as a dumping ground. If a class takes eight dependencies, it probably has too many responsibilities. DI exposes this problem. It doesn't cause it. Consider splitting the class.
- Letting dependencies reach back into the container. A class that receives a registry or
BuildContextand looks things up inside its methods has hidden dependencies again. Prefer to receive exactly the objects it needs. - Confusing DI with a singleton. DI says who supplies an object. It doesn't say how many instances exist. Lifetimes (one shared instance, or a new one per request) are a separate decision, covered in chapter 9.
What DI does not give you
DI doesn't make code correct, and it adds some cost.
- You write more constructor parameters and sometimes more types.
- Wiring errors move to runtime when you use a registry or the widget tree. A missing registration fails when the app runs, not when it compiles.
- Fakes can drift from the real implementation. A fake that always succeeds won't show you error handling bugs, so write fakes that can also fail on demand.
Weigh these costs against the benefit. For a small app with one screen and no tests, hard-coding may be reasonable. As the app grows, injection pays for itself.
Where this goes next
The remaining chapters build on the same example. You will pass dependencies through constructors, depend on abstractions, and assemble them in one place. Then you will deliver them through the widget tree with Provider, through a service locator with get_it, and through Riverpod. The final chapters cover testing with fakes and overrides, lifetimes and scopes, code generation, and how to choose between the approaches.
Exercise
A widget's build method contains final vm = ProfileViewModel(ApiUserRepository());. Name two problems with this line and say how you would restructure it.
Show answer
First, the view model and repository are recreated on every rebuild, which discards state and may open duplicate connections. Second, the widget is hard-wired to ApiUserRepository, so a widget test can't substitute a fake. Restructure by making ProfileViewModel accept a UserRepository (an abstract class) in its constructor, create the repository and view model once in the composition root (for example main() or a provider's create callback), and have the widget read the existing view model instead of constructing it.
Exercise
Does constructor injection require a DI package such as get_it or Riverpod?
Show answer
No. Constructor injection is plain Dart: the caller creates the dependency and passes it as an argument. Packages only help deliver objects to deeply nested places, manage lifetimes, or support overrides.