Sub topic 5
Providers with state and methods: Notifier and AsyncNotifier
This chapter assumes you can write a basic @riverpod function provider and run build_runner (covered in the previous chapters). It also assumes you know ConsumerWidget, ref.watch, and async/await in Dart. You will learn how to write providers whose state changes over time, and how to predict which provider type the generator produces.
Why a function is not enough
A functional provider computes a value from its inputs. It has no way for the UI to say "add this item" or "increment". When state must change in response to user actions, you need a place for both the state and the methods that change it. In Riverpod that place is a notifier.
A notifier is a class that owns one piece of state. The build method creates the initial state, and other methods replace it. The generator turns an annotated class into a provider and hides the base class and provider boilerplate.
A synchronous notifier
Here is the counter from the spine, with its imports:
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'counter.g.dart';
@riverpod
class Counter extends _$Counter {
@override
int build() => 0;
void increment() => state++;
void reset() => state = 0;
}Four things in this snippet matter:
- The class extends
_$Counter. The generator writes that base class intocounter.g.dart. Until you runbuild_runner, the file will not compile. buildis the only required member. It runs the first time someone reads the provider, and its return value becomes the initialstate.stateis a property the base class provides. Assigning to it replaces the state and notifies every listener.- The provider is named after the class:
counterProvider. The generator lowercases the first letter and addsProvider. A class namedCounterNotifierwould producecounterNotifierProvider.
In a widget, you use two different expressions for the two roles:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'counter.dart';
class CounterPage extends ConsumerWidget {
const CounterPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(counterProvider);
return Scaffold(
body: Center(child: Text('$count')),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(counterProvider.notifier).increment(),
child: const Icon(Icons.add),
),
);
}
}ref.watch(counterProvider) returns the state (an int) and rebuilds the widget when it changes. ref.read(counterProvider.notifier) returns the Counter object so you can call methods on it. Reading the notifier does not subscribe the widget to state changes, which is what you want inside a callback.
How the return type picks the provider type
You never choose NotifierProvider or AsyncNotifierProvider yourself. The generator looks at what build returns:
| `build` returns | Generated provider | Type of `state` |
|---|---|---|
| `T` | `NotifierProvider` | `T` |
| `Future<T>` | `AsyncNotifierProvider` | `AsyncValue<T>` |
| `Stream<T>` | `StreamNotifierProvider` | `AsyncValue<T>` |
Changing int build() to Future<int> build() async therefore changes the type of state and of what ref.watch returns, so every consumer must handle AsyncValue. The compiler reports those places, which is a useful way to find them.
The last arrow in the diagram is easy to miss. If build calls ref.watch on another provider and that provider changes, build runs again and the state resets to whatever build returns. We return to this below.
An asynchronous notifier
Most real notifiers load data. An AsyncNotifier is the same idea with an asynchronous build. The example below manages a todo list backed by a repository.
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'todos.g.dart';
class Todo {
const Todo({required this.id, required this.title});
final int id;
final String title;
}
abstract class TodoRepository {
Future<List<Todo>> fetchAll();
Future<void> add(String title);
}
class InMemoryTodoRepository implements TodoRepository {
final List<Todo> _items = [];
@override
Future<List<Todo>> fetchAll() async => List.unmodifiable(_items);
@override
Future<void> add(String title) async {
_items.add(Todo(id: _items.length + 1, title: title));
}
}
@Riverpod(keepAlive: true)
TodoRepository todoRepository(Ref ref) => InMemoryTodoRepository();
@riverpod
class TodoList extends _$TodoList {
@override
Future<List<Todo>> build() {
return ref.watch(todoRepositoryProvider).fetchAll();
}
Future<void> add(String title) async {
final repository = ref.read(todoRepositoryProvider);
state = const AsyncLoading();
state = await AsyncValue.guard(() async {
await repository.add(title);
return repository.fetchAll();
});
}
}The generator produces todoListProvider, an AsyncNotifierProvider. The repository is kept alive so the in-memory data survives while no widget listens to the list. The next section explains why that matters.
The add method follows a common pattern:
- Set
state = const AsyncLoading()so the UI can show a spinner. - Run the work inside
AsyncValue.guard. It catches any exception and returns anAsyncErrorinstead of throwing, and returnsAsyncDataon success. - Assign the result back to
state.
Because guard catches errors, a failing repository shows up as an error state in the UI instead of an unhandled exception in your method.
Showing the state
ref.watch(todoListProvider) returns an AsyncValue<List<Todo>>. Use when to handle all three cases:
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'todos.dart';
class TodoPage extends ConsumerWidget {
const TodoPage({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final todos = ref.watch(todoListProvider);
return Scaffold(
body: todos.when(
data: (items) => ListView(
children: [for (final todo in items) ListTile(title: Text(todo.title))],
),
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, stackTrace) => Center(child: Text('Failed: $error')),
),
floatingActionButton: FloatingActionButton(
onPressed: () => ref.read(todoListProvider.notifier).add('Write tests'),
child: const Icon(Icons.add),
),
);
}
}Using ref inside a notifier
A notifier has a ref property, available in build and in every method. The usual rules apply, with one extra twist for notifiers:
- In
build, useref.watchfor anything the state is derived from. When a watched provider changes,buildruns again. - In methods, use
ref.read. A method runs once per call and has no lifecycle to subscribe to, soref.watchthere would be a mistake. - Use
ref.listeninbuildwhen you want to react to another provider (for example, to log or to trigger a side effect) without rebuilding the notifier.
The consequence of the first rule deserves attention. Suppose build watches the current user, and the user logs out. build runs again, and any state you built up through methods is discarded. This is usually correct, because data for the old user should not outlive the user. If you want state to survive a dependency change, read the dependency with ref.read instead of ref.watch, and accept that you must refresh it yourself.
Pitfalls specific to notifiers
Mutating state in place
Riverpod decides whether to notify listeners by comparing the old and new state with ==. If you change the contents of a list and reassign the same list object, the comparison sees no change and nothing rebuilds:
// Wrong: same list instance, listeners may not be notified.
state.add(item);
state = state;
// Right: create a new list.
state = [...state, item];Treat state as immutable and always assign a new object. For int, String, and immutable classes, state++ or state = value is already safe.
Using state after an await
Between await calls, the provider may have been disposed, for example because the screen closed and nothing listens any more. Assigning to state on a disposed notifier throws. Providers from @riverpod are auto-dispose by default, so this is a realistic case for slow requests. Two defenses work:
- Mark the provider
@Riverpod(keepAlive: true)if its state should outlive its listeners. - Keep the awaited work short, and read everything you need from
refbefore the firstawait, asadddoes withrepository.
Reading `state` inside `build`
Do not read state in build to derive the initial value. On the first run it has not been set, and reading it throws. Compute the initial value from inputs only.
Stale generated code
If you rename the class, change the return type of build, or add a method that the generated file depends on, regenerate with dart run build_runner build. A symptom of a stale file is an error such as "Missing concrete implementation" or "The name _$Counter isn't a type", or a provider whose type no longer matches your code.
When to choose a notifier
Use a functional provider when the value is a pure function of other providers. Use a notifier when any of these is true:
- The UI must change the state (counters, form fields, a list the user edits).
- You need several related operations that share one piece of state.
- The state needs methods with side effects, such as saving to a repository and then updating the state.
A notifier is also easier to test, because you can call its methods through a ProviderContainer without any widgets. Later chapters build on this when they replace the repository with a fake.
Practice
Exercise
A provider is declared as @riverpod class Cart extends _$Cart { @override Future<List<String>> build() async => []; }. What is the name of the generated provider, which provider type is it, and what does ref.watch(cartProvider) return in a widget?
Show answer
The provider is cartProvider, named after the class with a lowercase first letter and a Provider suffix. Because build returns a Future<List<String>>, it is an AsyncNotifierProvider. ref.watch(cartProvider) returns an AsyncValue<List<String>>, which you handle with when or a switch on its data, loading and error cases. To call methods on the notifier, you use ref.read(cartProvider.notifier).
Exercise
A notifier holds List<String> as state. A teammate writes void add(String item) { state.add(item); } and the UI never updates. Explain why, and show the fix.
Show answer
The method mutates the existing list. The state object is the same instance, so Riverpod sees no change and does not notify listeners. Assign a new list instead: void add(String item) { state = [...state, item]; }.
Exercise
Inside the build method of a notifier, you call ref.watch(authProvider). The user logs out and the authProvider value changes. What happens to the notifier's state, and how would you avoid it if you wanted to keep the state?
Show answer
build runs again and the state is reset to whatever the new build returns, discarding changes made through methods. To keep the state, read authProvider with ref.read instead of ref.watch. The notifier then no longer rebuilds when auth changes, so you must refresh the data yourself when needed.