Sub topic 1
Async State in Riverpod with AsyncNotifier and AsyncValue
Prerequisites
You should know Dart async basics (Future, async, await, try/catch), Flutter widgets and the build method, and basic Riverpod use (Provider, ref.watch, ref.read).
Why async state needs more than a Future
A Future is a value that arrives later. Once it completes, it does not describe the steps before that point. A screen that loads data has three states: loading, success, and failure. A bare Future cannot tell the widget which of these applies, and it cannot hold the previous result while a new request runs.
AsyncValue: loading, data and error as one value
AsyncValue is a Riverpod type that wraps the state of an asynchronous operation. It has three variants: AsyncLoading, AsyncData, and AsyncError. A provider exposes one AsyncValue, so the widget reads one value and handles every case.
Rendering AsyncValue in widgets
Call when on the AsyncValue to map each variant to 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()),
);
}
}Declaring an AsyncNotifier and its provider
An AsyncNotifier owns async state. Its build method runs the first load and returns a Future. The provider connects the notifier to the widget tree.
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Todo {
const Todo(this.title);
final String title;
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
}
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();
}
}
final todosProvider =
AsyncNotifierProvider<TodosNotifier, List<Todo>>(TodosNotifier.new);Exercise
Why does TodoList call when instead of reading the list directly from the provider?
Show answer
The provider's state can be loading or failed, not only data. Reading the list directly would skip those cases. when forces the widget to handle loading, data and error.