Sub topic 5
Providers with state and methods: Notifier and AsyncNotifier
This chapter assumes you know Dart classes, async and await, ProviderScope, ConsumerWidget, and ref.watch. It also assumes that code generation is configured with riverpod_annotation, riverpod_generator, and build_runner.
A functional provider is a good fit when its value comes directly from a calculation or request. Use a class-based provider when the provider owns state and exposes actions that change that state.
Choosing Notifier or AsyncNotifier
Notifier<T> is a class-based provider whose state is a synchronous value of type T. Its build method returns the initial value.
AsyncNotifier<T> is a class-based provider whose state loads or changes asynchronously. Its build method returns FutureOr<T>. The public state is an AsyncValue<T>, so the UI can represent loading, data, and error states.
| Provider class | State exposed to widgets | Best for |
|---|---|---|
| `Notifier<int>` | `int` | Synchronous state and actions |
| `AsyncNotifier<List<Todo>>` | `AsyncValue<List<Todo>>` | Loading data and async mutations |
The generated provider name comes from the class name. A class named Counter produces counterProvider. A class named TodoList produces todoListProvider.
Building a synchronous Notifier
The class extends the generated private base class with the same name prefixed by _$. The build method initializes the state. Methods can then update state.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'counter.g.dart';
@riverpod
class Counter extends _$Counter {
@override
int build() => 0;
void increment() {
state++;
}
void decrement() {
if (state > 0) {
state--;
}
}
}After running the generator, a ConsumerWidget can read this provider:
class CounterText extends ConsumerWidget {
const CounterText({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(counterProvider);
return Text('$count');
}
}
class CounterButton extends ConsumerWidget {
const CounterButton({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
return ElevatedButton(
onPressed: () {
ref.read(counterProvider.notifier).increment();
},
child: const Text('Add'),
);
}
}ref.watch(counterProvider) rebuilds the widget when the integer changes. ref.read(counterProvider.notifier) gets the notifier object without watching it. Calling a notifier method changes the provider's state.
Building an AsyncNotifier
Use AsyncNotifier<T> when the initial state requires asynchronous work. With code generation, the class still extends _$ClassName; the generated base class supplies the correct AsyncNotifier behavior from the return type of build.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'todos.g.dart';
class Todo {
const Todo(this.title);
final String title;
}
@riverpod
class TodoList extends _$TodoList {
@override
Future<List<Todo>> build() async {
await Future<void>.delayed(const Duration(milliseconds: 300));
return const [
Todo('Read the Riverpod chapter'),
Todo('Run the generator'),
];
}
Future<void> add(String title) async {
final previous = state.valueOrNull ?? const <Todo>[];
state = const AsyncLoading();
state = await AsyncValue.guard(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
return [...previous, Todo(title)];
});
}
}The return type of build is Future<List<Todo>>, but widgets watch an AsyncValue<List<Todo>>. This lets the widget handle every result:
class TodoView extends ConsumerWidget {
const TodoView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todoListProvider);
return todos.when(
loading: () => const CircularProgressIndicator(),
error: (error, stackTrace) => Text('Error: $error'),
data: (items) => Column(
children: [
for (final item in items) Text(item.title),
ElevatedButton(
onPressed: () {
ref.read(todoListProvider.notifier).add('Write a test');
},
child: const Text('Add'),
),
],
),
);
}
}AsyncValue.guard runs a callback and converts either its result or thrown error into an AsyncValue. Assigning AsyncLoading before the operation gives the UI an explicit loading state. For more advanced interfaces, preserve the previous data while showing a refresh indicator instead of replacing it with an empty loading state.
How the lifecycle works
The build method is the provider's source of initial state. It can watch other providers through ref. If a watched dependency changes, Riverpod can rebuild this provider.
Keep provider methods focused on state transitions. Put network or database details in a repository provider when the logic grows. The notifier can watch that repository and coordinate its results.
Common mistakes
- Writing
final count = ref.read(counterProvider)in a widget that should rebuild. Usewatchfor displayed state. - Calling
ref.read(counterProvider.notifier)duringbuildto derive displayed data. Watch the provider's state instead. - Returning
AsyncLoadingfrom anAsyncNotifiermethod instead of assigning it tostate. - Forgetting to run
dart run build_runner buildorwatchafter changing an annotation or class shape. - Performing permanent side effects in
build. Riverpod may callbuildagain when dependencies change. - Treating
statein anAsyncNotifieras the raw list. It is anAsyncValue<List<Todo>>, so usestate.valueOrNull,when, or related helpers.
Exercise
Which provider class should you choose for a counter whose increment method changes an integer immediately, and which method should a widget call to increment it?
Show answer
Use a Notifier<int>. Watch counterProvider for the integer, then call ref.read(counterProvider.notifier).increment() to change it.