Sub topic 12
Injecting Repositories into View Models
This chapter assumes you can read Dart classes and async/await, know the difference between StatelessWidget and StatefulWidget, and have seen a view model built on ChangeNotifier. It uses the Todo, TodoRepository, and TodoListViewModel types from earlier chapters.
What dependency injection means
A view model needs a repository to get data. There are two ways it can obtain one:
- It creates the repository itself, for example
final _repository = InMemoryTodoRepository();. - It receives the repository from outside, usually as a constructor argument.
The second approach is dependency injection (DI). The view model declares what it needs and does not decide which implementation fills that need. The code that builds the view model makes that choice.
DI is a coding habit, not a framework. A constructor parameter is already DI. Packages such as provider only help you place and find objects in the widget tree.
Why it matters
A view model that builds its own repository has three problems:
- It cannot be tested alone. A unit test would hit the real network or database.
- It cannot be swapped. Moving from an in-memory repository to a REST one means editing the view model.
- It hides its requirements. You must read the class body to learn what it depends on.
The view model in this tutorial avoids all three:
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel({required TodoRepository repository})
: _repository = repository;
final TodoRepository _repository;
// ...
}The field type is the abstract TodoRepository, not InMemoryTodoRepository. The view model depends on an interface, so any class that implements it will work.
Constructor injection
Prefer constructor injection and mark the parameter required. The compiler then stops anyone from creating a view model without a repository.
Avoid these alternatives:
- Setters or public mutable fields. The object can exist half-configured, and you will meet
LateInitializationErrorat runtime. - Global singletons, such as
Repositories.todoread from inside the view model. The dependency is invisible in the constructor, and tests must reset global state between runs. - Service locators called from inside the view model. They have the same hidden-dependency problem. If you use a locator such as
get_it, call it at the composition point (see below), not inside the class.
The composition root
Somewhere, concrete classes must be chosen and connected. That place is the composition root. Keep it near the top of the app, usually main() or the widget that builds the app.
Only the composition root names InMemoryTodoRepository. Every other file refers to TodoRepository.
Manual injection without a package
For a small app you can pass objects by hand:
import 'package:flutter/material.dart';
void main() {
final repository = InMemoryTodoRepository();
final viewModel = TodoListViewModel(repository: repository);
runApp(MaterialApp(home: TodoScreen(viewModel: viewModel)));
}This works well until the view model has to be created and disposed with a screen's lifetime. Here viewModel lives for the whole app and is never disposed. That is acceptable for an app-wide object, but not for a per-screen one. The next section handles the per-screen case.
Injection with the provider package
The provider package places objects in the widget tree so that descendants can look them up. The call to context.read<T>() finds the nearest ancestor provider of type T.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
Provider<TodoRepository>(
create: (_) => InMemoryTodoRepository(),
child: const MaterialApp(home: TodoPage()),
),
);
}
class TodoPage extends StatelessWidget {
const TodoPage({super.key});
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) =>
TodoListViewModel(repository: context.read<TodoRepository>())..load(),
child: Scaffold(
appBar: AppBar(title: const Text('Todos')),
body: Consumer<TodoListViewModel>(
builder: (context, vm, _) {
if (vm.isLoading) {
return const Center(child: CircularProgressIndicator());
}
return ListView(
children: [
for (final todo in vm.todos)
CheckboxListTile(
title: Text(todo.title),
value: todo.done,
onChanged: (_) => vm.toggle(todo),
),
],
);
},
),
),
);
}
}Three details deserve attention.
The provider's type argument is the interface. Provider<TodoRepository> registers the object under the type TodoRepository. If you wrote Provider(create: (_) => InMemoryTodoRepository()) and let Dart infer the type, the registered type would be InMemoryTodoRepository, and context.read<TodoRepository>() would throw a ProviderNotFoundException. State the interface type explicitly.
Two providers, two lifetimes. The repository is registered once at the top and lives as long as the app. The view model is created by ChangeNotifierProvider when TodoPage enters the tree, and the provider calls dispose() on it when the page leaves the tree. This is why ChangeNotifierProvider suits per-screen view models.
read versus watch. Inside create, use context.read. It fetches the object once and does not subscribe to changes. context.watch in that position would be wrong, because create runs only once and the repository never notifies.
When to use which style
| Approach | Good for | Cost |
|---|---|---|
| Manual constructor passing | Small apps, tutorials, quick prototypes | You pass objects through many widget layers |
| `provider` | Shared repositories, per-screen view models | One extra package, and you must learn `read` and `watch` |
| Service locator at the composition root | Large apps with many layers | Easy to misuse by calling it from inside classes |
Start with the simplest option that fits. The view model itself is identical in all three cases, which is the point of DI.
Replacing the dependency in tests
The payoff of injection is that a test supplies a fake. The repository interface has two methods, so a fake is short:
import 'package:flutter_test/flutter_test.dart';
class FakeTodoRepository implements TodoRepository {
FakeTodoRepository(this.todos, {this.shouldFail = false});
List<Todo> todos;
final bool shouldFail;
@override
Future<List<Todo>> fetchTodos() async {
if (shouldFail) throw Exception('network down');
return List.of(todos);
}
@override
Future<void> setDone(int id, bool done) async {
todos = [
for (final t in todos) t.id == id ? t.copyWith(done: done) : t,
];
}
}
void main() {
test('the view model uses the injected repository', () async {
final fake = FakeTodoRepository([const Todo(id: 1, title: 'A')]);
final vm = TodoListViewModel(repository: fake);
await vm.load();
expect(vm.todos.single.title, 'A');
});
}No widget, network, or timer is involved, so the test runs in milliseconds. The next chapter covers testing in detail. Here the point is that the same constructor serves production and tests.
The same idea works in widget tests. Wrap the widget in Provider<TodoRepository>.value(value: fake, child: ...) and the real page runs against the fake.
Common errors
ProviderNotFoundException. The lookup type does not match the registered type, or the provider is not an ancestor of the widget callingread. Check the generic argument and the position in the tree.- Reading a provider in the same
buildthat creates it. Thecontextpassed toTodoPage.buildis above theChangeNotifierProviderit returns, socontext.read<TodoListViewModel>()there fails. UseConsumeror aBuilderto get a context below the provider. - Creating the view model inside
buildby hand. WritingTodoListViewModel(repository: repo)inbuildmakes a new object on every rebuild, which discards state and restarts loading. Create it ininitState, or letChangeNotifierProviderown it. - Injecting a concrete type. A parameter typed
InMemoryTodoRepositorycompiles, but tests can no longer pass any other implementation without subclassing it. - Injecting too much. If a constructor takes seven repositories, the view model probably does too many things. Consider splitting it.
Summary of the rules
- Depend on the interface, not the implementation.
- Receive dependencies through the constructor and mark them
required. - Choose concrete classes in one place, the composition root.
- Match each object's creation point to its lifetime: app-wide for repositories, per-screen for view models.
- Let tests build the same view model with a fake.
Exercise
A teammate writes Provider(create: (_) => InMemoryTodoRepository()) near the top of the app. Later, TodoPage calls context.read<TodoRepository>() inside the create of its ChangeNotifierProvider and throws ProviderNotFoundException. Explain why, and give the fix.
Show answer
Without an explicit type argument, Dart infers Provider<InMemoryTodoRepository>, so the object is registered under the concrete type. read<TodoRepository>() looks for the interface type and finds nothing. The fix is to write Provider<TodoRepository>(create: (_) => InMemoryTodoRepository(), ...). That also keeps the concrete class named only at the composition root.
Exercise
Why should a per-screen view model be created with ChangeNotifierProvider(create: ...) rather than constructed in the build method of a StatelessWidget?
Show answer
build can run many times, so a view model constructed there is recreated on each rebuild. That discards its state and restarts loading. ChangeNotifierProvider with create builds the object once for the provider's place in the tree and calls dispose() on it when the provider is removed.
Exercise
Write a FakeTodoRepository variant, or describe the change to the existing one, that lets a test check that toggle records an error when setDone fails.
Show answer
Add a second flag such as shouldFailOnSet and throw in setDone when it is true, for example if (shouldFailOnSet) throw Exception('write failed');. The test builds the view model with that fake, awaits vm.toggle(todo), and expects vm.error to be non-null.