Sub topic 3
Rendering `AsyncValue` in Widgets
This chapter assumes you know Dart Future, async, and await, Flutter’s build method, and basic Riverpod usage with ProviderScope, ref.watch, and ref.read. It also assumes that todosProvider exposes an AsyncValue<List<Todo>>.
An AsyncValue<T> represents the current state of an asynchronous operation. The type parameter T is the successful result. For example, AsyncValue<List<Todo>> can represent:
AsyncLoading: the list is not ready yet.AsyncData<List<Todo>>: the list loaded successfully.AsyncError: loading failed and includes the error and stack trace.
The widget must render all three cases. Treating only the successful case leaves users with a blank screen while data loads or when a request fails.
Use `when` for clear state handling
AsyncValue.when takes one function for each state. It returns the widget that should be displayed for the current state.
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 load todos: $error'),
),
data: (items) => ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index].title),
);
},
),
);
}
}The data callback receives the successful value. The error callback receives both the error object and its StackTrace. The stack trace is useful for logging, even if the UI shows a shorter message.
Do not put the request itself inside build. Watching the provider is enough. Riverpod decides when the widget needs to rebuild because the provider changes from loading to data or error.
| State | Callback | Typical widget |
|---|---|---|
| Loading | `loading` | `CircularProgressIndicator` |
| Successful result | `data` | List, text, or detail view |
| Failed request | `error` | Error message and retry control |
Use pattern matching when each branch is small
Dart 3 pattern matching provides another way to inspect an AsyncValue. This style works well when the branches return short expressions.
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(),
};
}
}AsyncData(:final value) extracts the successful value. AsyncError(:final error) extracts the error. The wildcard branch handles loading and any state not matched by the earlier patterns.
Pattern matching is concise, but when often communicates the three required UI states more directly. Choose one style for a widget rather than mixing both.
Make errors useful
An error message should tell the user what happened and what they can do next. A raw exception string is often useful during development but may be confusing in production.
A retry button can invalidate the provider. Invalidation marks the current value as stale so Riverpod can run the provider again when it is read.
class TodoErrorView extends ConsumerWidget {
const TodoErrorView({required this.error, super.key});
final Object error;
@override
Widget build(BuildContext context, WidgetRef ref) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Todos are unavailable: $error'),
const SizedBox(height: 8),
ElevatedButton(
onPressed: () => ref.invalidate(todosProvider),
child: const Text('Try again'),
),
],
),
);
}
}You can use this widget in the error branch:
return todos.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, _) => TodoErrorView(error: error),
data: (items) => TodoItems(items: items),
);Here, TodoItems would be a separate widget responsible for displaying the successful list.
Exercise
Why should a ConsumerWidget render loading, data, and error instead of assuming that ref.watch always returns usable data?
Show answer
An asynchronous provider changes state over time. It starts without a result, can finish with data, or can finish with an error. Handling all three states prevents blank screens, crashes, and missing feedback.