Sub topic 12
Injecting Repositories into View Models
Assume you know Dart classes, constructors, Future, async/await, Flutter widget lifecycles, and ChangeNotifier. This chapter focuses on dependency injection: giving a view model the repository it needs instead of creating that repository inside the view model.
Why inject a repository?
A repository is the data boundary used by a view model. It may load data from an API, database, or local cache. The view model should depend on the repository interface, not on one specific implementation.
This separation gives you:
- Easier unit tests with a fake repository.
- The ability to replace an API implementation with a cache.
- A clear place to configure application-wide services.
- View models that describe behavior without knowing how data is stored.
Constructor injection is the simplest form of dependency injection. The dependency is passed to the constructor.
| Object | Responsibility |
|---|---|
| `TodoRepository` | Defines operations for todo data |
| `ApiTodoRepository` | Implements those operations with a server |
| `TodoListViewModel` | Converts repository results into UI state |
| Widget tree | Creates and connects the objects |
Constructor injection
The view model accepts a TodoRepository. It does not call ApiTodoRepository directly.
import 'package:flutter/foundation.dart';
class Todo {
const Todo({required this.id, required this.title});
final int id;
final String title;
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
}
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel({required TodoRepository repository})
: _repository = repository;
final TodoRepository _repository;
List<Todo> _todos = const [];
bool _isLoading = false;
Object? _error;
List<Todo> get todos => List.unmodifiable(_todos);
bool get isLoading => _isLoading;
Object? get error => _error;
Future<void> load() async {
_isLoading = true;
_error = null;
notifyListeners();
try {
_todos = await _repository.fetchTodos();
} catch (error) {
_error = error;
} finally {
_isLoading = false;
notifyListeners();
}
}
}The interface is the contract. Any class with a compatible implementation can be passed to the view model. The private field prevents widgets from replacing the repository after construction.
Compose dependencies at the application boundary
Create concrete objects near main, where the application is assembled. This location is sometimes called the composition root.
With Provider, the repository can be registered above the view model:
MultiProvider(
providers: [
Provider<TodoRepository>(
create: (_) => ApiTodoRepository(),
),
ChangeNotifierProvider(
create: (context) => TodoListViewModel(
repository: context.read<TodoRepository>(),
),
),
],
child: const TodoApp(),
)Use Provider for ordinary dependencies and ChangeNotifierProvider for objects whose changes widgets must observe. The provider creates and disposes the view model when its subtree owns that object.
Replacing the repository in tests
A test can pass a fake repository that returns fixed data or throws a controlled error. The view model then runs as plain Dart, without a widget tree or network connection.
Exercise
Why should a view model receive a TodoRepository instead of constructing one internally?
Show answer
Constructor injection keeps the view model independent of a concrete data source, so production code can use a real repository and tests can use a fake one.