Sub topic 14
Structuring an app around repositories and providers
This chapter assumes you can write a Notifier and an AsyncNotifier, read providers with ref.watch and ref.read, and handle an AsyncValue in a widget. Earlier chapters showed each piece alone. Here you arrange them into a layout that stays readable as the app grows.
The problem with fetching in widgets
A quick way to load data is to call an HTTP client or database from a widget or from a notifier. This works for a demo, but it causes three problems:
- You cannot test the widget without the network or the database.
- Several screens end up repeating the same parsing and error handling.
- Swapping the data source, for example from a REST API to a local cache, means editing UI code.
The usual fix is to split the app into three layers and give each layer one job.
| Layer | Contains | Knows about |
|---|---|---|
| Data | Repositories, API clients, database access | Storage and network details |
| State | Providers, `Notifier`, `AsyncNotifier` | Repositories, other providers |
| UI | `ConsumerWidget` classes | Providers only |
Each layer depends only on the one below it. Widgets never import a repository class, and repositories never import Flutter or Riverpod.
Step 1: define the repository as an interface
A repository is a plain Dart class that hides where data comes from. Declare an abstract class so that other code depends on the contract instead of one implementation.
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 InMemoryTodoRepository implements TodoRepository {
final _items = <Todo>[const Todo(1, 'Read the chapter')];
@override
Future<List<Todo>> fetchAll() async {
await Future<void>.delayed(const Duration(milliseconds: 300));
return List.of(_items);
}
@override
Future<void> add(String title) async {
_items.add(Todo(_items.length + 1, title));
}
}
final todoRepositoryProvider = Provider<TodoRepository>(
(ref) => InMemoryTodoRepository(),
);fetchAll returns a copy with List.of, so callers cannot mutate the repository's internal list by accident.
todoRepositoryProvider is the seam of the whole design. A plain Provider creates its value once per container and keeps it, so every reader shares one InMemoryTodoRepository and the stored items survive between reads. A real implementation would build an HTTP client here, or read it from another provider with ref.watch.
Step 2: put the logic in a notifier that watches the repository
The notifier turns repository calls into UI state. It gets the repository through ref, not through a constructor argument or a global.
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);The two reads differ on purpose. Inside build, ref.watch makes the notifier rebuild if the repository provider ever changes, for example when a test or a login flow replaces it. Inside add, which runs in response to a user action, ref.read fetches the repository once with no subscription.
The await future at the end of add makes the method complete only after the reload finishes. A caller that awaits add can then show a confirmation or close a dialog at the right moment.
Step 3: keep derived values in providers, not widgets
Counts, filters, and sorted views belong in the state layer. A derived provider recomputes only when its input changes, and any widget can reuse it.
final todoCountProvider = Provider<int>((ref) {
final todos = ref.watch(todoListProvider);
return todos.maybeWhen(data: (items) => items.length, orElse: () => 0);
});Here maybeWhen supplies a value for the loading and error states. Without orElse, you would have to write all three branches.
Step 4: keep widgets thin
A widget reads state, draws it, and forwards user actions. It does not know whether a repository talks to a server.
import 'package:flutter/material.dart';
class TodoPage extends ConsumerWidget {
const TodoPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todoListProvider);
final count = ref.watch(todoCountProvider);
return Scaffold(
appBar: AppBar(title: Text('Todos ($count)')),
body: todos.when(
data: (items) => ListView(
children: [for (final t in items) ListTile(title: Text(t.title))],
),
error: (error, stackTrace) => Center(child: Text('Failed: $error')),
loading: () => const Center(child: CircularProgressIndicator()),
),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(todoListProvider.notifier).add('New todo'),
child: const Icon(Icons.add),
),
);
}
}
void main() {
runApp(const ProviderScope(child: MaterialApp(home: TodoPage())));
}The Todos ($count) title shows 0 while the list loads. If that flicker bothers you, return null from the derived provider while loading and handle it in the title.
Choosing where the real implementation is wired in
There are two common ways to connect a concrete repository, and each has a cost.
| Approach | How it works | Trade-off |
|---|---|---|
| Default in the provider | `Provider<TodoRepository>((ref) => ApiTodoRepository(...))` | Simple, but tests must override it to avoid real I/O |
| Throwing placeholder | The provider throws `UnimplementedError`, and `ProviderScope` or the test supplies the value | Forgetting the override fails loudly, but every entry point must override it |
Use the default when one implementation is correct in production. Use the placeholder when the implementation needs something created before the app starts, such as an opened database. In that case, main creates the object and passes it in:
final todoRepositoryProvider = Provider<TodoRepository>(
(ref) => throw UnimplementedError('Override todoRepositoryProvider'),
);
Future<void> main() async {
final repository = InMemoryTodoRepository(); // e.g. await openDatabase()
runApp(
ProviderScope(
overrides: [todoRepositoryProvider.overrideWithValue(repository)],
child: const MaterialApp(home: TodoPage()),
),
);
}Suggested folder layout
Group files by feature first and by layer second. Each feature then owns its repository, providers, and widgets:
lib/features/todos/data/todo_repository.dartholds the interface, the implementations, and the repository provider.lib/features/todos/application/todo_list.dartholds the notifier and derived providers.lib/features/todos/presentation/todo_page.dartholds the widgets.
A feature may import another feature's providers, but not its widgets or its repository implementation.
Common mistakes
- Reading a repository inside a widget. If a widget calls
ref.read(todoRepositoryProvider)directly, it skips the notifier and its state. The UI does not update, and the loading and error handling is lost. Route actions through a notifier method. - Letting the repository depend on
Ref. A repository that takes aRefties the data layer to Riverpod and makes it harder to test as plain Dart. Pass in what it needs, such as an HTTP client, when you build it inside the provider. - Putting state in the repository. A repository fetches and saves. If it also caches a "current list" that the UI depends on, that value changes without any provider noticing, and the screen goes stale. Keep observable state in notifiers.
- Skipping the interface. With only a concrete class, overriding in tests means subclassing it and its real constructor. The abstract class makes a fake a few lines long.
Why this layout pays off in tests
Because the only way to reach data is todoRepositoryProvider, a test replaces that one provider and everything above it uses the fake. The next chapter does exactly that with ProviderContainer and overrideWithValue. The layout also makes feature changes cheap. Moving from the in-memory repository to a REST one means writing a new class and changing one line in the provider, with no changes to the notifier or the widgets.
Exercise
In the layout above, why does TodoList.build use ref.watch(todoRepositoryProvider) while TodoList.add uses ref.read(todoRepositoryProvider)?
Show answer
build is a reactive context. Watching the repository provider lets the notifier rebuild and reload if the repository is replaced or changes. add runs once in response to a user action, so it only needs the current repository. Using ref.read there avoids creating a subscription that would be pointless outside build.
Exercise
You need a completedTodosProvider that returns only finished todos, and the Todo class needs a done field. Which layers change, and where should the filtering code live?
Show answer
Add the done field to Todo and update the repository implementation in the data layer. Put the filtering in a derived Provider in the state layer that watches todoListProvider and returns items.where((t) => t.done).toList(). The widget then only watches completedTodosProvider and draws the result, with no filtering logic of its own.