Sub topic 9
Loading, updating and refreshing with AsyncNotifier
This chapter assumes Dart futures, async and await, Flutter widget basics, and the difference between watch and read. AsyncNotifier is useful when a provider both loads asynchronous data and exposes methods that change that data.
The working model
An AsyncNotifier<T> manages a value of type T whose loading can take time. Its build method loads the initial value. Riverpod represents the result as an AsyncValue<T> with three main states:
AsyncLoading: the operation has not finished.AsyncData: the operation returned a value.AsyncError: the operation failed.
A repository is an object responsible for reading and writing data. The notifier depends on the repository, but the widget does not need to know how the repository works.
Implementing loading and mutation
The provider below uses an abstract repository. In a real application, an override can supply an API or database implementation.
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);
}
final todoRepositoryProvider = Provider<TodoRepository>(
(ref) => throw UnimplementedError('Provide a TodoRepository'),
);
class TodoList extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() {
final repository = ref.watch(todoRepositoryProvider);
return repository.fetchAll();
}
Future<void> add(String title) async {
final repository = ref.read(todoRepositoryProvider);
await repository.add(title);
ref.invalidateSelf();
await future;
}
}
final todoListProvider =
AsyncNotifierProvider<TodoList, List<Todo>>(TodoList.new);
class TodoView extends ConsumerWidget {
const TodoView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todoListProvider);
return todos.when(
loading: () => const CircularProgressIndicator(),
error: (error, stackTrace) => Text('Could not load todos: $error'),
data: (items) => ListView(
children: [
for (final todo in items) ListTile(title: Text(todo.title)),
],
),
);
}
}ref.watch inside build makes the notifier depend on the repository. If that dependency changes, Riverpod rebuilds the notifier. The add method uses ref.read because the method needs the repository once and should not rebuild while it runs.
ref.invalidateSelf() marks the notifier for refresh. Riverpod calls build again, so the list is read from the repository instead of being manually reconstructed. await future waits until that refresh finishes. This keeps the provider's data consistent with the repository.
Common errors
A frequent mistake is reading state as if it were a List<Todo>. In an AsyncNotifier, state is an AsyncValue<List<Todo>>, so it may represent loading or failure. Let the view handle these states with when.
Another mistake is calling ref.watch inside a button callback. Use watch for reactive values needed during build, and read for event-driven actions such as add, save, or delete.
Exercise
Why does the add method call ref.invalidateSelf() after writing to the repository?
Show answer
It makes AsyncNotifier run build again, so the provider displays freshly loaded repository data.