Sub topic 14
Structuring an App Around Repositories and Providers
This chapter assumes you know Dart classes, generics, Future, and async/await. You should also understand Flutter widgets and the basics of Riverpod providers, ref.watch, and AsyncValue.
A small app can put network calls directly in a widget. That approach becomes difficult to test and change. A repository is a class that hides where data comes from. It might call an HTTP API, read a database, or return cached data. The provider layer connects that repository to the user interface.
Separate responsibilities
Keep each layer focused:
| Layer | Responsibility | Should know about |
|---|---|---|
| Widget | Displays state and sends user actions | Providers and Flutter |
| Provider or notifier | Coordinates state and operations | Repository interfaces |
| Repository | Loads and saves domain data | API, database, or cache |
| Data source | Performs external I/O | Network or storage details |
The widget should not construct an HTTP client or decide how todos are stored. The notifier should not contain layout code. This separation makes each part easier to replace.
Define the repository boundary
Start with a model and an abstract repository. The abstract class is the boundary used by the provider. Production code can supply an API implementation, while tests can supply a fake.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Todo {
const Todo(this.id, this.title);
final int id;
final String title;
}
abstract class TodoRepository {
Future<List<Todo>> fetchAll();
Future<void> add(String title);
}
class MemoryTodoRepository implements TodoRepository {
final _items = <Todo>[
const Todo(1, 'Read the Riverpod chapter'),
];
@override
Future<List<Todo>> fetchAll() async => List.of(_items);
@override
Future<void> add(String title) async {
_items.add(Todo(_items.length + 1, title));
}
}
final todoRepositoryProvider = Provider<TodoRepository>(
(ref) => MemoryTodoRepository(),
);
class TodoList extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() {
return ref.watch(todoRepositoryProvider).fetchAll();
}
Future<void> add(String title) async {
await ref.read(todoRepositoryProvider).add(title);
ref.invalidateSelf();
await future;
}
}
final todoListProvider =
AsyncNotifierProvider<TodoList, List<Todo>>(TodoList.new);
class TodoListPage extends ConsumerWidget {
const TodoListPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todoListProvider);
return Scaffold(
appBar: AppBar(title: const Text('Todos')),
body: todos.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, stackTrace) => Center(child: Text('$error')),
data: (items) => ListView(
children: [
for (final todo in items)
ListTile(title: Text(todo.title)),
],
),
),
);
}
}
void main() {
runApp(
const ProviderScope(
child: MaterialApp(home: TodoListPage()),
),
);
}build loads the initial state. The add method performs a write through the repository, then invalidates the notifier. Invalidating it runs build again, so the UI receives fresh data through the same loading, error, and data states.
Choose where dependencies enter
Providers are useful dependency declarations. A notifier asks for the repository through ref, rather than constructing it itself. Tests can then override todoRepositoryProvider with a fake repository without changing notifier code.
Use ref.watch for dependencies whose changes should rebuild or recreate the current provider. Use ref.read for an operation, such as calling add, when you do not want to subscribe to that provider's value.
Exercise
Why should TodoList use a repository instead of calling an HTTP client directly?
Show answer
The repository hides the data source and gives the notifier a small, testable interface. Tests can replace it with a fake, and the data source can change without changing the notifier or widget.