Sub topic 7
Changing state with AsyncValue.guard
This chapter assumes you know Dart async/await and try/catch, and that you have written a basic Riverpod Provider. It also assumes you have read the earlier chapters on AsyncValue and on loading initial data in an AsyncNotifier's build() method. By the end you will be able to write mutation methods that never leave the provider stuck in a loading state.
The problem: mutations can fail too
build() gives you the initial value. Most screens also change data: add a todo, delete one, toggle a flag. Each change calls a repository, which is a Future that can fail.
Riverpod catches errors thrown inside build() for you and turns them into an AsyncError. Mutation methods are different. They are ordinary methods on your notifier, so Riverpod does not wrap them. You must decide what happens to state when the call succeeds and when it throws.
The usual mutation has three steps:
- Set
statetoAsyncLoadingso the UI can show progress. - Run the asynchronous work.
- Set
statetoAsyncDatawith the result, or toAsyncErrorif the work threw.
Step 3 is where bugs appear. If an exception escapes and nothing sets state, the UI shows a spinner forever. AsyncValue.guard exists to make that bug hard to write.
What AsyncValue.guard does
AsyncValue.guard is a static method. It takes a function that returns a Future<T>, runs it, and returns a Future<AsyncValue<T>>. It never throws.
- If the future completes with a value, you get
AsyncData(value). - If the future throws anything, you get
AsyncError(error, stackTrace).
You assign that result to state, and both outcomes are handled in one line.
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();
state = await AsyncValue.guard(() async {
await repository.addTodo(title);
return repository.fetchTodos();
});
}
}
final todosProvider =
AsyncNotifierProvider<TodosNotifier, List<Todo>>(TodosNotifier.new);Read addTodo line by line:
ref.read(todoRepositoryProvider)happens before anyawait. This is a mutation triggered by a user action, soref.readis correct here.ref.watchbelongs inbuild().state = const AsyncLoading()publishes the loading state. Any widget watchingtodosProviderrebuilds.- The closure passed to
guardadds the todo and then fetches the fresh list. Its return value becomes the newList<Todo>. await AsyncValue.guard(...)produces anAsyncValue<List<Todo>>, and the assignment publishes it.
The method returns Future<void>. Callers can await it to know when the mutation has finished, but they do not get the result or the error from it. Both live in state.
The same code without guard
This method does exactly what guard does, written out by hand. It is a method of TodosNotifier.
Future<void> addTodoManually(String title) async {
final repository = ref.read(todoRepositoryProvider);
state = const AsyncLoading();
try {
await repository.addTodo(title);
state = AsyncData(await repository.fetchTodos());
} catch (error, stackTrace) {
state = AsyncError(error, stackTrace);
}
}Comparing the two shows what guard saves you.
| Concern | Manual `try`/`catch` | `AsyncValue.guard` |
|---|---|---|
| Catches errors and stack traces | You write `catch (error, stackTrace)` | Built in |
| Wraps success in `AsyncData` | You write `AsyncData(...)` | Built in |
| Easy to forget a branch | Yes, for example a missing `catch` | No, both outcomes are always produced |
| Lines per mutation | About 8 | About 5 |
Use the manual form when you need a side effect in only one branch, such as logging a failure before storing the error. Otherwise guard is shorter and harder to get wrong.
State transitions during a mutation
The provider moves through a small set of states on each call. Failure is an ordinary transition, not a crash.
An AsyncError produced by guard is not final. The next mutation, or a reload, replaces it.
What guard does not catch
guard only protects the closure you give it. Three common mistakes leave parts of your method unprotected.
- Work outside the closure. If
repository.addTodo(title)is awaited before theguardcall, a throw there escapes the method. Put everything that can fail inside the closure. - Synchronous code before the first
await. Validation such asif (title.isEmpty) throw ArgumentError(...)placed aboveguardthrows out ofaddTodoto the caller. Either put it inside the closure or return early without touchingstate. - Forgetting to assign the result.
await AsyncValue.guard(...)on its own line runs the work and discards the outcome. The provider stays inAsyncLoading.
// Bug: the guarded result is thrown away, so state stays AsyncLoading.
await AsyncValue.guard(() => repository.addTodo(title));
// Correct: assign the result.
state = await AsyncValue.guard(() => repository.addTodo(title));The buggy line also has a type problem. The closure returns Future<void>, so the result would be an AsyncValue<void>. Assigning it to a notifier of List<Todo> fails to compile, which at least flags the mistake. Return the new list from the closure, as the main example does.
guard also accepts an optional second argument, a test function. If test returns false for a thrown error, guard rethrows it instead of converting it. This is useful when you want some failures, such as a cancelled request, to propagate rather than become UI state.
Keeping the list visible while a mutation runs
state = const AsyncLoading() replaces the current value. A widget that uses when will show the loading branch, so the existing list disappears and a spinner takes its place. For "add todo" that flicker is usually unwanted.
AsyncLoading can carry the previous value. copyWithPrevious builds a loading state that remembers what was there before:
Future<void> addTodoKeepingList(String title) async {
final repository = ref.read(todoRepositoryProvider);
state = const AsyncLoading<List<Todo>>().copyWithPrevious(state);
state = await AsyncValue.guard(() async {
await repository.addTodo(title);
return repository.fetchTodos();
});
}The new state still reports isLoading == true, but it also holds the old list, so state.value returns it. A widget can read state.value and draw the list with a small progress indicator on top. The next chapter covers how isLoading, isRefreshing, and isReloading differ and how when treats each, so this chapter stops at the mechanism.
Surfacing mutation errors in the UI
A failed mutation puts the provider into AsyncError. If the screen renders with when, the error branch replaces the list. That is correct for a failed initial load. For a failed "add", you probably want to keep the screen and show a message.
ref.listen reacts to state changes without rebuilding the widget. It is the right tool for one-off effects such as snackbars.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class AddTodoButton extends ConsumerWidget {
const AddTodoButton({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.listen<AsyncValue<List<Todo>>>(todosProvider, (previous, next) {
if (next is AsyncError) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Could not add todo: ${next.error}')),
);
}
});
return FloatingActionButton(
onPressed: () => ref.read(todosProvider.notifier).addTodo('New todo'),
child: const Icon(Icons.add),
);
}
}Two details matter here:
- The button calls
ref.read(todosProvider.notifier).addTodo(...). Event handlers useref.read, neverref.watch. - The listener fires on every change, including the initial
AsyncLoading. Thenext is AsyncErrorcheck filters for the failure only.
After the snackbar, the provider is still in AsyncError, so a when-based list shows the error branch. If you want the old list to stay visible after a failed mutation, you need a different design. One option is to keep the list in AsyncData and report mutation errors through a separate provider. This is a design decision, not something guard solves for you.
Safety around await
A mutation spends time at an await, and the provider can change during that time. Three habits keep this safe.
- Read dependencies first. Call
ref.readfor the repository before the firstawait, as the examples do. Usingrefrepeatedly after long awaits is legal while the provider is alive, but resolving dependencies up front makes the method's inputs obvious. - Do not use
BuildContextafter an await inside the notifier. The notifier has no context. Keep UI work, such as snackbars, in the widget and drive it from state withref.listen. - Expect overlapping calls. If the user taps "add" twice, two mutations run at once. Whichever finishes last writes
statelast. Disable the button whilestate.isLoadingis true, or serialize calls in the notifier, if order matters.
Verifying the behavior
You can check that guard captures a failure by overriding the repository with a fake that throws. This test uses a ProviderContainer, and the Todo and TodoRepository types from the first example in this chapter. The next chapters return to testing in more detail.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class FailingRepository implements TodoRepository {
@override
Future<List<Todo>> fetchTodos() async => const [Todo('1', 'Existing')];
@override
Future<void> addTodo(String title) async {
throw StateError('server unavailable');
}
}
void main() {
test('a failing addTodo leaves the provider in AsyncError', () async {
final container = ProviderContainer(
overrides: [
todoRepositoryProvider.overrideWithValue(FailingRepository()),
],
);
addTearDown(container.dispose);
await container.read(todosProvider.future);
await container.read(todosProvider.notifier).addTodo('Ship it');
final state = container.read(todosProvider);
expect(state.hasError, isTrue);
expect(state.error, isA<StateError>());
});
}The call await ...addTodo('Ship it') completes normally, with no exception. The failure is visible only through state, which is the behavior you want from guard.
Common mistakes
- Writing
state = await repository.fetchTodos()withoutguardortry/catch. A thrown error leaves the provider inAsyncLoading. - Setting
AsyncLoadingand never leaving it because the result ofguardwas not assigned. - Using
ref.watchinside a mutation method. This is a hard error in recent Riverpod versions and is wrong in any case. - Showing a full-screen spinner for every mutation because
AsyncLoadingwas set withoutcopyWithPrevious. - Expecting
addTodoto throw. It reports failures throughstate, so callers must observestateor useref.listen.
Summary
A mutation on an AsyncNotifier follows a fixed shape: publish AsyncLoading, run the work inside AsyncValue.guard, and assign the result back to state. guard returns AsyncData on success and AsyncError on any throw, so the provider cannot be left in a stuck loading state. Put all failing work inside the closure. Use copyWithPrevious to keep old data on screen, and ref.listen to turn failures into one-off UI effects.
Exercise
A teammate writes this method. The UI spinner never goes away when the server returns an error. Name the bug and rewrite the method so that both success and failure end the loading state. Future<void> removeCompleted() async { final repository = ref.read(todoRepositoryProvider); state = const AsyncLoading(); await AsyncValue.guard(() => repository.fetchTodos()); }
Show answer
The result of AsyncValue.guard is awaited but never assigned to state, so state stays AsyncLoading whether the call succeeds or fails. The fix is to assign it: state = await AsyncValue.guard(() => repository.fetchTodos());. Because the closure returns the list, the assignment type-checks. A failure then produces an AsyncError and a success produces an AsyncData, and both end the loading state.
Exercise
You want addTodo to keep the current list visible while the request runs. Which one line replaces state = const AsyncLoading(), and what does state.value return while the request is in flight?
Show answer
Use state = const AsyncLoading<List<Todo>>().copyWithPrevious(state);. The state reports isLoading as true, but state.value still returns the previous List<Todo>, so the widget can keep drawing the list.