Sub topic 9
Loading, updating and refreshing with AsyncNotifier
This chapter assumes you know Notifier, NotifierProvider, ref.watch and ref.read. It also assumes you know Dart Future and async/await, and that you have met AsyncValue through FutureProvider. You will learn how to load data in build, change it with methods, and refresh it. You will also learn how the AsyncValue state behaves during each step.
Why AsyncNotifier exists
A FutureProvider is good for data you only read. Many screens also need to change that data: add a todo, delete a row, submit a form. A plain FutureProvider has no place to put those methods.
AsyncNotifier<T> fills that gap. It works like Notifier<T>, with three differences:
buildreturnsFuture<T>(orFutureOr<T>) instead ofT.- The exposed state is
AsyncValue<T>, notT. - The class can have methods that change
state.
The provider type is AsyncNotifierProvider<NotifierClass, T>. Widgets see AsyncValue<T>, the same type they get from FutureProvider.
The states of AsyncValue
An AsyncValue<T> is always one of three cases: AsyncLoading, AsyncData or AsyncError. It can also carry the previous value or error while a new one loads. This is what makes refreshing smooth.
While the state is loading for the second time, AsyncValue still holds the old data. isLoading is true, and hasValue and value still return the old result. The isRefreshing flag is true in this case.
Loading data in build
The provider calls build the first time something listens to it. The returned future decides the state: loading until it completes, then data or error.
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('Override todoRepositoryProvider'),
);
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);Three details matter here:
buildusesref.watchfor the repository. If the repository provider changes,buildruns again. This is the same rule as in a derived provider.addusesref.read. Methods run once in response to an event, so they should not subscribe to anything.refandstateare available on the notifier.futureis a getter on the notifier that returns aFuture<List<Todo>>. It completes with the next value of the state.
Updating: two strategies
After a write, the list on screen is out of date. You can fix this in two ways.
Strategy 1: invalidate and rebuild
ref.invalidateSelf() marks the provider as stale. The notifier's build runs again, so the list is fetched fresh from the source. The line await future makes add wait until that new fetch finishes. Without it, add would return while the state was still loading, and a caller that awaits add would continue too early.
This is the simplest option and always matches the server. The cost is one extra network call per write.
Strategy 2: assign the new state yourself
If the write returns the new data, or you can compute it, assign it to state and skip the second request. AsyncValue.guard runs a future and turns a thrown error into an AsyncError, so you do not need a try/catch.
class TodoListGuarded extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() {
return ref.watch(todoRepositoryProvider).fetchAll();
}
Future<void> add(String title) async {
final repo = ref.read(todoRepositoryProvider);
state = await AsyncValue.guard(() async {
await repo.add(title);
return repo.fetchAll();
});
}
}If add throws, the whole list is replaced by an AsyncError, and the screen shows the error branch instead of the old list. For a failed write that is often too harsh. See the optimistic update section below for a gentler pattern.
Refreshing
Refreshing means loading the data again without the screen jumping back to a spinner. There are three tools:
| Call | What it does | Returns |
|---|---|---|
| `ref.invalidate(provider)` | Marks the provider stale. It rebuilds when it is next read, or right away if something is listening. | `void` |
| `ref.refresh(provider)` | Invalidates and reads the new value immediately. | The new state |
| `ref.refresh(provider.future)` | Same, but gives you the `Future` to await. | `Future<T>` |
Use ref.invalidate when you do not need the result. Use ref.refresh(provider.future) when something must wait for the reload, such as a pull-to-refresh indicator:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class TodoScreen extends ConsumerWidget {
const TodoScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todoListProvider);
return RefreshIndicator(
onRefresh: () => ref.refresh(todoListProvider.future),
child: todos.when(
data: (items) => ListView(
children: [for (final t in items) ListTile(title: Text(t.title))],
),
error: (error, stackTrace) => ListView(
children: [ListTile(title: Text('Failed: $error'))],
),
loading: () => const Center(child: CircularProgressIndicator()),
),
);
}
}The ListView in the error branch is deliberate. RefreshIndicator needs a scrollable child, or the user cannot pull to retry.
What the user sees during a refresh
AsyncValue.when has three flags that decide which branch runs while a reload is in progress:
skipLoadingOnRefreshdefaults totrue. During a refresh or invalidate,whenkeeps callingdatawith the old value.skipLoadingOnReloaddefaults tofalse. When the provider rebuilds because a watched dependency changed,whencallsloading.skipErrordefaults tofalse. An error with a previous value still callserror.
So after ref.invalidateSelf() in add, the list stays visible, which is usually what you want. Check todos.isRefreshing if you want a small progress bar on top of the stale list.
Optimistic updates and rollback
An optimistic update shows the result before the server confirms it. If the request fails, you restore the old list.
class OptimisticTodoList extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() {
return ref.watch(todoRepositoryProvider).fetchAll();
}
Future<void> add(String title) async {
final repo = ref.read(todoRepositoryProvider);
final previous = state.requireValue;
state = AsyncData([...previous, Todo(previous.length + 1, title)]);
try {
await repo.add(title);
} catch (_) {
state = AsyncData(previous);
rethrow;
} finally {
ref.invalidateSelf();
}
}
}requireValue throws if the state has no value yet, so call add only when data has loaded. The finally block invalidates so the list syncs with the server in both outcomes. The rethrow lets the UI show an error message.
Common errors
- Using
ref.watchinside a method. Insideaddit is wrong. Useref.read. Riverpod asserts on this in debug mode. - Forgetting
await futureafterinvalidateSelf. The method returns before the data arrives, so loading indicators on buttons flicker off too early. - Reading
state.valuewhile loading.valueisnullon the first load. UsevalueOrNull(or handle the loading case explicitly) when the data may be absent. - Assigning state after the notifier is disposed. If an
autoDisposeprovider loses its last listener during anawait, a later assignment tostatethrows. Checkref.mountedwhere your Riverpod version supports it, or keep the provider alive while the operation runs. - Putting side effects in
build.buildcan run many times. Writes belong in methods.
Exercise
A screen watches todoListProvider and shows a spinner whenever when calls loading. After the user pulls to refresh, the spinner never appears and the old list stays visible until the new one arrives. Is this a bug, and how would you show a thin progress bar during the refresh?
Show answer
It is not a bug. skipLoadingOnRefresh defaults to true, so when keeps calling the data branch with the previous value while a refresh runs. To show a progress bar, read todos.isRefreshing (or todos.isLoading together with todos.hasValue) in the widget and display a LinearProgressIndicator above the list while it is true.
Exercise
In add, you replace await future; with nothing. The caller does await notifier.add('x'); showDoneMessage();. What goes wrong, and why?
Show answer
ref.invalidateSelf() only schedules a rebuild. Without await future, add returns right away while the state is still the old data in a loading state. showDoneMessage() then runs before the new list has loaded, so the message can appear while the list is still stale. Awaiting future makes add finish only after the rebuilt state completes.