Sub topic 7
Repositories as the Single Source of Truth
Assume you know basic Dart classes, async/await, Future, and Flutter widget lifecycle. You should also be familiar with setState and why large widgets become difficult to maintain when they contain data-access code.
A repository is a class that owns access to application data. The data might come from an HTTP service, a database, or local storage. The view model asks the repository for data without knowing where that data comes from.
“Single source of truth” means that one component defines how data is read and changed. Other layers do not keep competing copies or make direct requests to the service.
The repository boundary
A typical MVVM data flow looks like this:
Each layer has a focused responsibility:
| Layer | Responsibility |
|---|---|
| View | Displays state and sends user actions |
| View model | Converts data into UI state |
| Repository | Defines and coordinates data access |
| Service or storage | Performs HTTP, database, or file operations |
The repository interface is the boundary that the view model uses. The interface makes the view model independent from a particular server or database.
Define a model and repository
A model represents one piece of application data. Making it immutable means its fields cannot change after construction. To update an item, create a new instance with copyWith.
class Todo {
const Todo({
required this.id,
required this.title,
this.done = false,
});
final int id;
final String title;
final bool done;
Todo copyWith({String? title, bool? done}) {
return Todo(
id: id,
title: title ?? this.title,
done: done ?? this.done,
);
}
}
abstract interface class TodoRepository {
Future<List<Todo>> fetchTodos();
Future<void> setDone(int id, bool done);
}
class InMemoryTodoRepository implements TodoRepository {
final List<Todo> _todos = [
const Todo(id: 1, title: 'Write the view model'),
const Todo(id: 2, title: 'Connect the view'),
];
@override
Future<List<Todo>> fetchTodos() async {
await Future<void>.delayed(const Duration(milliseconds: 200));
return List.unmodifiable(_todos);
}
@override
Future<void> setDone(int id, bool done) async {
final index = _todos.indexWhere((todo) => todo.id == id);
if (index == -1) {
throw ArgumentError('Unknown todo: $id');
}
_todos[index] = _todos[index].copyWith(done: done);
}
}
Future<void> main() async {
final repository = InMemoryTodoRepository();
print(await repository.fetchTodos());
await repository.setDone(1, true);
print(await repository.fetchTodos());
}The view model can now call fetchTodos and setDone. Replacing InMemoryTodoRepository with an HTTP implementation does not require changing the view model.
Avoid competing data sources
A repository should return consistent data and protect its internal collection. Returning List.unmodifiable prevents callers from adding or removing items behind the repository’s back.
Do not let widgets call an API client directly. That creates multiple paths for loading and updating data. It also makes error handling and testing inconsistent.
Repositories can also combine several services. For example, they might fetch a remote list, save it locally, and return one Todo collection to the view model. The view model still depends on the repository contract, not on those implementation details.
Exercise
What should change in the view model when the todo data moves from memory to a REST API?
Show answer
Ideally, nothing. Create another TodoRepository implementation that performs the API calls and inject it into the view model.