Sub topic 7
Changing State with `AsyncValue.guard`
This chapter assumes you know Dart Future, async, await, and try/catch. It also assumes basic Riverpod usage, including AsyncNotifier, ref.read, and provider overrides.
Loading data in build() handles the initial request. Real screens also change data. A user might add a todo, save a profile, or delete a message. Each operation can succeed or fail, so the notifier must update its state for both outcomes.
Why mutations need explicit state updates
An AsyncNotifier does not automatically know that a repository operation is in progress. Your mutation method must set the state to loading, perform the operation, and store the result.
A bare Future<void> does not tell the widget whether the operation is currently running or whether it failed. AsyncValue gives the widget one value that represents all three outcomes.
| State | Meaning | Typical UI |
|---|---|---|
| `AsyncLoading` | The operation is running | Progress indicator or disabled button |
| `AsyncData` | The operation completed successfully | Updated content |
| `AsyncError` | The operation failed | Error message and retry action |
Using `AsyncValue.guard`
AsyncValue.guard runs an asynchronous function and converts its result into an AsyncValue.
- If the function completes,
guardreturnsAsyncDatacontaining the result. - If the function throws,
guardreturnsAsyncErrorcontaining the exception and stack trace. - The error is stored in provider state instead of requiring a separate
try/catchblock.
Here is a notifier that adds a todo and then fetches the complete list again:
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);
}
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<List<Todo>>();
state = await AsyncValue.guard(() async {
await repository.addTodo(title);
return repository.fetchTodos();
});
}
}
final todosProvider =
AsyncNotifierProvider<TodosNotifier, List<Todo>>(TodosNotifier.new);The method performs two asynchronous actions. First, it writes the new todo. Second, it reads the list again. The final AsyncData therefore contains the server's current list rather than a manually guessed local list.
The method does not throw when the repository fails. Instead, AsyncValue.guard creates an AsyncError and assigns it to state. A widget watching todosProvider can render that error.
Rendering the mutation result
A widget can use the same when method for the state produced by build() and by addTodo():
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class TodoList extends ConsumerWidget {
const TodoList({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todosProvider);
return todos.when(
loading: () => const Center(
child: CircularProgressIndicator(),
),
error: (error, stackTrace) => Center(
child: Text('Could not save or load todos: $error'),
),
data: (items) => ListView(
children: [
for (final todo in items)
ListTile(title: Text(todo.title)),
],
),
);
}
}This simple approach replaces the list with a loading indicator during the mutation. That is correct, but it may not be the best user experience. A later chapter discusses refreshing and reloading states, which can keep previous data visible while a request runs.
A button can start the mutation through the notifier:
ElevatedButton(
onPressed: () {
ref.read(todosProvider.notifier).addTodo('Read Riverpod docs');
},
child: const Text('Add todo'),
)If the operation needs form validation, validate before calling the notifier. If the caller must react to failure directly, the notifier can expose a separate result policy, but storing the error in provider state is usually enough for screen-level feedback.
The state transition
The operation follows this sequence:
The important rule is that every path ends in a meaningful AsyncValue. The widget never has to guess whether the request is still running or why it failed.
Exercise
What state will todosProvider contain if repository.addTodo throws inside the AsyncValue.guard callback?
Show answer
It will contain an AsyncError with the thrown error and its stack trace. The exception is captured by guard, and the notifier assigns that error value to state.