Sub topic 4
Declaring an AsyncNotifier and its provider
This chapter assumes you know Dart Future, async and await, and basic Riverpod: Provider, ref.watch and ref.read. You should also have seen AsyncValue and when from the earlier chapters. Here you learn how to declare the class that owns asynchronous state and the provider that exposes it. The next chapters cover what goes inside build(), how to change state, and how to reload.
What an AsyncNotifier is
A plain FutureProvider can load a value, but it has no place for methods that change that value. An AsyncNotifier<T> adds one. It is a class with two jobs:
- Its
build()method produces the initial value of typeT, usually by awaiting something. - Its other methods change the state, for example "add a todo" or "toggle a flag".
The state is always an AsyncValue<T>. While build() runs it is AsyncLoading. When build() returns it becomes AsyncData<T>. If build() throws, it becomes AsyncError. You never create these states for the initial load yourself. Riverpod does it for you.
An AsyncNotifier is not a widget and holds no UI. It is plain Dart that talks to a repository, which makes it easy to test.
The two declarations
Every async notifier needs two pieces: the notifier class and a global provider that creates it.
class TodosNotifier extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() {
return ref.watch(todoRepositoryProvider).fetchTodos();
}
}
final todosProvider =
AsyncNotifierProvider<TodosNotifier, List<Todo>>(TodosNotifier.new);Each part of this has a specific role:
extends AsyncNotifier<List<Todo>>fixes the type of the data. The state isAsyncValue<List<Todo>>.build()is the only member you must override. Its return type may be aFuture<T>or a plainT. The base class declares it as returningFutureOr<T>, so a synchronous return is allowed. When you can, keep the more specificFuture<T>return type so the intent is clear.AsyncNotifierProvider<TodosNotifier, List<Todo>>takes two type arguments: the notifier class and the data type. If they disagree, the code does not compile.TodosNotifier.newis a constructor tear-off. The provider calls it to create the notifier. Passing a function instead of an instance lets Riverpod decide when to create the object.
The provider is declared as a top-level final variable. Providers are only descriptions. The state lives in a ProviderContainer (inside ProviderScope in a Flutter app), not in the variable.
The two ways to read the provider
The same provider gives you two different objects, and mixing them up is the most common beginner error.
| Expression | Returns | Use it for |
|---|---|---|
| `ref.watch(todosProvider)` | `AsyncValue<List<Todo>>` | Rendering. The widget rebuilds when the state changes. |
| `ref.read(todosProvider.notifier)` | `TodosNotifier` | Calling methods such as `addTodo`, usually from callbacks. |
| `ref.read(todosProvider.future)` | `Future<List<Todo>>` | Awaiting the loaded value. A later chapter covers it. |
The .notifier object never changes while the provider is alive, so watching it would not rebuild anything useful. Call methods through ref.read(todosProvider.notifier).
// Rendering: rebuilds when the AsyncValue changes.
final todos = ref.watch(todosProvider);
// Acting: gets the notifier once, then calls a method.
onPressed: () => ref.read(todosProvider.notifier).addTodo('Buy milk'),What lives inside the notifier
Inside the class you get three members from the base class:
refgives access to other providers and to lifecycle hooks. You useref.watchinbuild()andref.readin methods.stateis the currentAsyncValue<T>. You read and assign it to publish a new state. Assigning a new value notifies every listener.futureis aFuture<T>that completes when the state is next resolved. A later chapter returns to it.
ref is not available while the constructor runs, so do not use it in a field initializer. Do that work inside build() or in a method.
The notifier instance is not recreated every time the state changes. When a watched dependency changes, Riverpod calls build() again on the notifier it already has. Fields you put on the class are therefore not reset on every rebuild. Treat build() as the place where all state is (re)initialized, and keep long-lived data in state rather than in extra fields.
Injecting the repository
The notifier above never constructs its repository. It asks for one through todoRepositoryProvider. This is the pattern that makes the class testable and keeps the data source swappable.
final todoRepositoryProvider = Provider<TodoRepository>((ref) {
throw UnimplementedError('Override with a real repository');
});The default provider throws on purpose. Any container that forgets to override it fails loudly instead of silently using a wrong implementation. Because the throw happens while build() runs, it appears as an AsyncError state, not as a crash. The widget shows its error branch. That is a useful signal when you see "Override with a real repository" on screen.
You supply the real object where the app starts:
void main() {
runApp(
ProviderScope(
overrides: [
todoRepositoryProvider.overrideWithValue(InMemoryTodoRepository()),
],
child: const MyApp(),
),
);
}How the pieces connect
The notifier is created lazily. Nothing runs when the provider is declared. build() first runs when something reads or watches todosProvider. If nothing listens afterwards, a non-auto-dispose provider keeps its state until the container is disposed.
A complete runnable example
This program wires everything together. It uses an in-memory repository with a short delay so you can see the loading spinner. It needs flutter_riverpod in pubspec.yaml, and you can run it as lib/main.dart.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Todo {
const Todo(this.id, this.title);
final String id;
final String title;
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
Future<void> addTodo(String title);
}
class InMemoryTodoRepository implements TodoRepository {
final List<Todo> _todos = [const Todo('1', 'Read the docs')];
@override
Future<List<Todo>> fetchTodos() async {
await Future<void>.delayed(const Duration(milliseconds: 800));
return List.of(_todos);
}
@override
Future<void> addTodo(String title) async {
_todos.add(Todo('${_todos.length + 1}', title));
}
}
final todoRepositoryProvider = Provider<TodoRepository>((ref) {
throw UnimplementedError('Override with a real repository');
});
class TodosNotifier extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() {
return ref.watch(todoRepositoryProvider).fetchTodos();
}
Future<void> addTodo(String title) async {
final repository = ref.read(todoRepositoryProvider);
state = const AsyncLoading();
state = await AsyncValue.guard(() async {
await repository.addTodo(title);
return repository.fetchTodos();
});
}
}
final todosProvider =
AsyncNotifierProvider<TodosNotifier, List<Todo>>(TodosNotifier.new);
void main() {
runApp(
ProviderScope(
overrides: [
todoRepositoryProvider.overrideWithValue(InMemoryTodoRepository()),
],
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: TodoScreen());
}
}
class TodoScreen extends ConsumerWidget {
const TodoScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todosProvider);
return Scaffold(
appBar: AppBar(title: const Text('Todos')),
body: todos.when(
data: (items) => ListView(
children: [
for (final todo in items) ListTile(title: Text(todo.title)),
],
),
error: (error, stackTrace) => Center(child: Text('Failed: $error')),
loading: () => const Center(child: CircularProgressIndicator()),
),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(todosProvider.notifier).addTodo('New todo'),
child: const Icon(Icons.add),
),
);
}
}On launch you see a spinner for about 800 milliseconds, then one todo. Tapping the button calls addTodo through the notifier. The list briefly shows the spinner again and then shows two todos. The addTodo body is explained in the chapter on AsyncValue.guard. For now, notice that it assigns to state, and the widget updates because it watches the provider.
Choosing between related providers
Several provider types can hold async data. The right choice depends on whether the state has to change from the outside.
| Provider | Use when | Limitation |
|---|---|---|
| `FutureProvider` | The value is only loaded, never changed by your code. | No methods. You can only reload it. |
| `AsyncNotifierProvider` | The value is loaded and also changed by methods. | You write a class. |
| `NotifierProvider` | State is synchronous, with no loading phase. | No `AsyncValue`. |
| `StreamProvider` | The value comes from a stream. | You do not set state yourself. |
If you start with a FutureProvider and later need an addTodo method, converting to an AsyncNotifier is a small change. The widgets that watch the provider still receive an AsyncValue and keep working unchanged.
Common errors
- Wrong type arguments.
AsyncNotifierProvider<TodosNotifier, Todo>for a notifier that extendsAsyncNotifier<List<Todo>>fails to compile. The second argument must match the class's type argument exactly. - Constructing the notifier yourself. Writing
TodosNotifier()and calling its methods gives you an object with norefand no state. Always get it fromref.read(todosProvider.notifier). - Watching the notifier to call methods.
ref.watch(todosProvider.notifier)compiles but does not rebuild on state changes. It is also easy to confuse with watching the state. Usereadin callbacks. - Calling
ref.readfor rendering.ref.read(todosProvider)in abuildmethod returns the current value once and never rebuilds. Useref.watch. - Using
reftoo early. A field such asfinal repo = ref.read(...)fails becauserefdoes not exist yet. Move it intobuild()or a method. - Expecting synchronous data.
ref.watch(todosProvider)is never aList<Todo>. It is anAsyncValuethat can be loading or failed, even when the repository is fast.
Notes on lifecycle and versions
By default the provider keeps its state while the container lives. If you want state discarded when no widget watches it, declare the provider with AsyncNotifierProvider.autoDispose. If the notifier needs a parameter, such as a user id, Riverpod offers a family variant of the provider.
Exercise
A teammate writes final todos = ref.read(todosProvider); inside a ConsumerWidget.build method and complains that the list never updates after a todo is added. What is wrong, and how do you fix it?
Show answer
ref.read returns the current AsyncValue once and does not subscribe to changes, so the widget never rebuilds when the state changes. Change it to ref.watch(todosProvider). Keep ref.read(todosProvider.notifier) for calling methods from callbacks such as onPressed.
Exercise
Write the declaration of a notifier CounterNotifier whose state is an AsyncValue<int> and whose build() returns the value from a Future<int> loadCount() function, plus the provider named counterProvider.
Show answer
class CounterNotifier extends AsyncNotifier<int> { @override Future<int> build() => loadCount(); } final counterProvider = AsyncNotifierProvider<CounterNotifier, int>(CounterNotifier.new);
Exercise
You run the example app but forget the overrides list in ProviderScope. What do you see on screen, and why does the app not crash?
Show answer
The error branch shows a message containing "Override with a real repository". The default todoRepositoryProvider throws while build() is running. Riverpod catches the exception and stores it as AsyncError, so when renders the error callback.