Sub topic 7
Repositories as the single source of truth
This chapter assumes you know Dart async code, the Todo model from the earlier chapters, and that a view model extends ChangeNotifier. It covers what a repository owns, how it differs from a service, and how to build one that caches data and keeps it consistent.
What "single source of truth" means
Several parts of an app often need the same data. A list screen shows todos, a detail screen shows one todo, and a badge counts the unfinished ones. If each view model calls the network on its own and keeps its own copy, the copies drift apart. You complete a todo on one screen and the others still show it as open.
A repository prevents this. It is the one object in the data layer that decides where data comes from, how long it stays valid, and how changes are applied. View models ask the repository for data and never talk to the network or storage directly. Whatever the repository returns is the app's current answer.
Repository versus service
A service is a thin wrapper around one external API, such as an HTTP client, a database, or a platform plugin. It knows the wire format and nothing else. A repository sits above one or more services and turns their raw output into domain models.
| Concern | Service | Repository | View model |
|---|---|---|---|
| Speaks HTTP, SQL, or JSON | Yes | No | No |
| Returns domain models such as `Todo` | No | Yes | Reads them |
| Decides caching and refresh | No | Yes | No |
| Combines several data sources | No | Yes | No |
| Holds loading and error flags for the UI | No | No | Yes |
| Knows about widgets | No | No | No |
The last column matters. A repository reports failure by throwing an exception or returning a result. The view model turns that into isLoading and error state for the view.
The repository interface
The view model should depend on an interface, not on a concrete class. This is the interface from the earlier chapters:
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
Future<void> setDone(int id, bool done);
}The interface expresses what the app needs in domain terms: "give me todos" and "mark this one done". It says nothing about REST, SQLite, or JSON field names. You can swap the implementation without touching any view model, and tests can supply a fake.
A service and a caching repository
The next program is plain Dart and runs as shown. The service speaks a JSON-like row format with a field called completed. The repository hides that detail, maps rows to Todo, and keeps an in-memory cache.
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}) =>
Todo(id: id, title: title ?? this.title, done: done ?? this.done);
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
Future<void> setDone(int id, bool done);
}
/// Stands in for an HTTP client. It knows rows, not domain models.
class TodoService {
final List<Map<String, Object?>> _rows = [
{'id': 1, 'title': 'Write the view model', 'completed': false},
{'id': 2, 'title': 'Connect the view', 'completed': false},
];
int fetchCount = 0;
Future<List<Map<String, Object?>>> getAll() async {
fetchCount++;
await Future<void>.delayed(const Duration(milliseconds: 100));
return [for (final row in _rows) Map<String, Object?>.of(row)];
}
Future<void> patchCompleted(int id, bool completed) async {
await Future<void>.delayed(const Duration(milliseconds: 100));
final row = _rows.firstWhere(
(r) => r['id'] == id,
orElse: () => throw ArgumentError('Unknown todo $id'),
);
row['completed'] = completed;
}
}
class CachedTodoRepository implements TodoRepository {
CachedTodoRepository(this._service);
final TodoService _service;
List<Todo>? _cache;
@override
Future<List<Todo>> fetchTodos() async {
final cached = _cache;
if (cached != null) return cached;
final rows = await _service.getAll();
final todos = List<Todo>.unmodifiable([
for (final row in rows) _fromRow(row),
]);
_cache = todos;
return todos;
}
@override
Future<void> setDone(int id, bool done) async {
await _service.patchCompleted(id, done);
final cached = _cache;
if (cached != null) {
_cache = List<Todo>.unmodifiable([
for (final t in cached) t.id == id ? t.copyWith(done: done) : t,
]);
}
}
Todo _fromRow(Map<String, Object?> row) => Todo(
id: row['id'] as int,
title: row['title'] as String,
done: row['completed'] as bool,
);
}
Future<void> main() async {
final service = TodoService();
final repository = CachedTodoRepository(service);
await repository.fetchTodos();
await repository.setDone(1, true);
final todos = await repository.fetchTodos();
for (final todo in todos) {
print('${todo.title}: ${todo.done}');
}
print('service calls: ${service.fetchCount}');
}Running it prints:
Write the view model: true
Connect the view: false
service calls: 1The second fetchTodos call never reached the service. The cache answered it, and setDone had already updated the cached copy.
Why the order in `setDone` matters
setDone calls the service first and updates the cache only afterwards. If the service call throws, the exception propagates and the cache stays unchanged. The cache never claims a change the server rejected. The cost is latency: the UI waits for the round trip before it sees the new value.
Updating the cache first (an optimistic update) feels faster, but then you must roll back on failure. Start with the simple order and move to optimistic updates only when the delay is noticeable.
How a request travels
The diagram shows one read and one write. Only the first read pays for a network call.
Design rules for repositories
Follow these rules to keep the repository a reliable source of truth:
- Return immutable data. The repository hands out
List.unmodifiableand immutableTodoobjects. A view model cannot change the cache by accident, because the cache only changes through repository methods. - Keep one instance per data set. The cache is useful only if every view model shares the same repository object. Create it once and inject it, as the dependency injection chapter shows. Two instances mean two caches and the drift you wanted to avoid.
- Translate at the boundary. Field names like
completed, date strings, and status codes stop at the repository. The rest of the app seesTodo.done. - Keep UI concerns out. A repository has no
BuildContext, noChangeNotifier, and no loading flag. The view model owns those. - Decide how errors surface. Throwing is the simplest approach and the one this tutorial uses. Wrap service exceptions in a domain-specific type if you do not want view models to know about
SocketException.
Edge cases to handle
- Concurrent first loads. If two view models call
fetchTodosbefore the first call finishes, both see an empty cache and both hit the service. Fix this by storing the in-flightFutureand returning it to later callers. - Failed loads. In the example, a failed
getAllleaves_cacheasnull, so the next call retries. That is the behavior you want. Do not cache a failure unless you also decide when to retry. - Unknown IDs. The service throws
ArgumentErrorfor an id it does not know. The exception passes through the repository to the view model, which already records it in itserrorfield. - Partial updates. If one write touches both the service and local storage, decide which one is authoritative. Write to the authority first and update the other from its result.
When the repository is not enough
A repository that only forwards calls to a service adds a layer and no value. That is acceptable when you expect the data source to change or want a clean seam for testing. If a feature will always read from one endpoint with no caching and no mapping, a thin repository is still cheap. Do not add logic to it just to justify its existence.
Exercise
Two view models, a list screen and a counter badge, each create their own CachedTodoRepository. The user completes a todo on the list screen and the badge count does not change. Name the cause and the fix.
Show answer
Each view model has its own repository and therefore its own cache, so the badge repository never learns about the change. Create one CachedTodoRepository at the top of the app and inject the same instance into both view models. The repository then holds the only copy of the data.
Exercise
In CachedTodoRepository.fetchTodos, two callers invoke the method at the same moment on an empty cache. How many service calls happen, and how would you reduce them to one?
Show answer
Two. Both calls see _cache == null and each awaits its own getAll. Store the pending Future<List<Todo>> in a field when the first call starts and return that same future to any caller that arrives before it completes. Clear the field if the request fails so a later call can retry.