Sub topic 3
Rendering AsyncValue in widgets
This chapter assumes you know Dart's Future, async and await, Flutter's build method, and the basics of Riverpod (Provider, ref.watch, ref.read). Dart 3 pattern matching helps for one section. The examples use the Todo class and todosProvider from the earlier chapters. The API names follow Riverpod 2.x. Where Riverpod 3 differs, the text says so.
What a widget receives
When you call ref.watch(todosProvider) on an AsyncNotifierProvider<TodosNotifier, List<Todo>>, you get an AsyncValue<List<Todo>>. It is never a Future and never a bare list. It is a sealed class with three subtypes:
AsyncLoading: work is in progress.AsyncData: a value is available.AsyncError: the last attempt failed, and the object carries the error and the stack trace.
A widget's build method is synchronous, so it cannot await. Riverpod does the waiting for you and hands the widget a snapshot of the current state. When the state changes, the widget rebuilds with a new snapshot. Your job in the widget is to decide what to draw for each case.
You can inspect the snapshot with these members:
| Member | Meaning |
|---|---|
| `isLoading` | A computation is running now. It can be true even when old data exists. |
| `hasValue` | A value is stored, possibly an old one. |
| `hasError` | An error is stored, possibly alongside an old value. |
| `valueOrNull` | The value, or `null` if none (Riverpod 2.x). Riverpod 3 renames this to `value`. |
| `requireValue` | The value, or a thrown `StateError` if none. Use it only when you know data is present, such as in tests. |
| `error` and `stackTrace` | The stored error details, or `null`. |
The key idea is that these flags are independent. An AsyncValue can be loading and also hold the previous data. That combination is what makes "keep old content visible during a reload" possible, and the rest of this chapter depends on it.
Rendering with when
AsyncValue.when takes one callback per case and returns whatever the callbacks return, usually a widget.
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(
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()),
);
}
}All three callbacks are required, so the compiler stops you from forgetting the error case. That is the main reason to prefer when over checking flags by hand.
Related methods:
maybeWhentakes anorElsecallback, so you supply only the cases you care about.whenOrNullreturnsnullfor any case you omit. This is handy when a widget should draw nothing for loading or error.maphands you theAsyncData,AsyncErrorandAsyncLoadingobjects instead of unpacked values. You need it only when you want to inspect the wrapper itself.
Rendering with a switch expression
Dart 3 patterns let you replace when with a switch expression. You can destructure the subtypes directly:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class TodoCount extends ConsumerWidget {
const TodoCount({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todosProvider);
return switch (todos) {
AsyncData(:final value) => Text('${value.length} todos'),
AsyncError(:final error) => Text('Error: $error'),
_ => const CircularProgressIndicator(),
};
}
}The _ arm catches AsyncLoading. Because the class is sealed, you can instead list AsyncLoading() explicitly and drop the wildcard. The compiler then checks that every case is covered.
Choose between the two styles by what you need:
whenhas options for loading behavior, described in the next section.- A switch expression composes better with other patterns. You can match on conditions, such as
AsyncData(:final value) when value.isEmpty, to draw an empty-state message.
An empty list is AsyncData with a zero-length list, not a separate state. Handling it is your job inside the data case.
What happens when data already exists
The first load has no previous value, so when calls loading. Later reloads are different. Suppose the user pulls to refresh, or a provider you watch changes. The provider recomputes, and the snapshot becomes AsyncLoading carrying the old data or error.
You must decide whether the UI should flash back to a spinner or keep showing the old list. when gives you two switches for this:
| Parameter | Default (Riverpod 2.x) | Effect when `true` |
|---|---|---|
| `skipLoadingOnRefresh` | `true` | During a refresh, `when` ignores the loading flag and calls `data` or `error` with the previous result. |
| `skipLoadingOnReload` | `false` | During a reload, `when` does the same. |
| `skipError` | `false` | If an error arrived while old data exists, `when` calls `data` with the old value. |
A refresh is a recompute forced by ref.refresh or ref.invalidate while nothing the provider depends on changed. A reload is a recompute caused by a dependency change, for example a watched filter provider. The two cases are separate flags, isRefreshing and isReloading, and a later chapter covers them in detail. For rendering, you only need to know that both set isLoading to true while the old data is still available.
The following diagram shows how when picks a callback in Riverpod 2.x.
To keep the old list on screen during reloads and still signal activity, combine skipLoadingOnReload with a progress bar:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class TodoListWithProgress extends ConsumerWidget {
const TodoListWithProgress({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todosProvider);
return Column(
children: [
if (todos.isLoading && todos.hasValue)
const LinearProgressIndicator(),
Expanded(
child: todos.when(
skipLoadingOnReload: true,
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()),
),
),
],
);
}
}The bar appears only when a value exists and a computation is running. The first load still shows the full-screen spinner, because hasValue is false then.
Reacting to errors with ref.listen
Rendering an error in place is not always what you want. After a failed "add todo" action, the list itself should stay on screen, and the user needs a transient message such as a snackbar. Showing a snackbar inside build would repeat it on every rebuild. Use ref.listen instead, which runs a callback when the value changes and does not draw anything:
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) {
ref.listen<AsyncValue<List<Todo>>>(todosProvider, (previous, next) {
if (next.hasError && !next.isLoading) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Something went wrong: ${next.error}')),
);
}
});
final todos = ref.watch(todosProvider);
return Scaffold(
appBar: AppBar(title: const Text('Todos')),
body: todos.when(
skipError: true,
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()),
),
);
}
}Two details matter here. ref.listen must be called from build of a ConsumerWidget, and Riverpod removes the listener when the widget goes away. The !next.isLoading check avoids reacting to a snapshot that still holds an old error while a retry is under way.
skipError: true makes when show the previous data when a newer attempt failed. If no previous data exists, such as when the very first load fails, when still calls error.
Common errors
- Using
requireValuein a widget. It throws if the provider is still loading or failed. Reserve it for tests and for code paths that are guaranteed to run after a successful load. - Reading
valueOrNulland treatingnullas "empty".nullmeans "no value yet or failed", not "no items". Handle the empty list in the data case. - Calling
ref.read(todosProvider)inbuild. It returns a snapshot once and never rebuilds the widget. Useref.watchfor anything drawn on screen. - Rebuilding the whole tree for one flag. If a widget cares only about whether an error exists, use
ref.watch(todosProvider.select((v) => v.hasError)). The widget then rebuilds only when that boolean changes. - Expecting a spinner on every reload. With the defaults, a refresh keeps the old data. If you see no spinner after
ref.invalidate, this is why. CheckisLoadingyourself, as in the progress bar example. - Swallowing the stack trace. The
errorcallback receives it. Log it or send it to your crash reporter instead of printing only the message.
Summary of the decision
- Use
whenwhen you want a required callback for each state and fine control over loading behavior. - Use a
switchexpression when you want pattern guards or a compact form, and accept that you handle loading yourself. - Use
ref.listenfor one-off reactions such as snackbars and navigation. - Check
isLoadingtogether withhasValueto draw a progress indicator over existing content.
Exercise
A user pulls to refresh. Your code calls ref.invalidate(todosProvider), and the old list stays on screen with no indicator, although a request is in flight. Which when default explains this, and how do you show activity without hiding the list?
Show answer
Invalidating the provider while nothing it depends on has changed is a refresh, and skipLoadingOnRefresh defaults to true in Riverpod 2.x. So when ignores the loading flag and calls data with the previous list. To show activity, check the flags yourself and draw an indicator over the list, for example if (todos.isLoading && todos.hasValue) const LinearProgressIndicator(), above the when result.
Exercise
Write a switch expression over AsyncValue<List<Todo>> todos that returns Text('Nothing to do') for an empty list, Text('N todos') for a non-empty list, Text('Error: ...') for an error, and a CircularProgressIndicator while loading, with no wildcard arm.
Show answer
switch (todos) {
AsyncData(:final value) when value.isEmpty => const Text('Nothing to do'),
AsyncData(:final value) => Text('${value.length} todos'),
AsyncError(:final error) => Text('Error: $error'),
AsyncLoading() => const CircularProgressIndicator(),
}
The guarded arm comes before the general AsyncData arm. Because AsyncValue is sealed, the compiler accepts the switch as exhaustive without _.
Exercise
Why is it a bug to call ScaffoldMessenger.of(context).showSnackBar(...) directly inside build when todos.hasError is true, and what should you use instead?
Show answer
build can run many times for the same error, for example on any rebuild caused by a parent, so the snackbar would show repeatedly. Use ref.listen on the provider. Its callback runs when the value changes, not on each rebuild, and it is the right place for side effects such as snackbars and navigation.