Sub topic 6
Mutable state with Notifier and NotifierProvider
This chapter assumes you can write Dart classes with generics, know the basics of ConsumerWidget and WidgetRef, and know the difference between ref.watch and ref.read. Here you will build state that changes over time. A plain Provider is read-only, so it cannot do this.
What a Notifier is
A Notifier<T> is a class that owns one piece of state of type T. It has three parts:
- A
build()method that returns the initial state. - A
stateproperty. Assigning a new value to it notifies every listener. - Public methods that change
state. These are the only way the outside world should change it.
A NotifierProvider<NotifierType, StateType> exposes the notifier to the widget tree. Riverpod creates the notifier lazily, the first time something reads the provider. It stores the instance in the nearest ProviderContainer, which ProviderScope creates for you.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Counter extends Notifier<int> {
@override
int build() => 0;
void increment() => state++;
void reset() => state = 0;
}
final counterProvider = NotifierProvider<Counter, int>(Counter.new);
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),
),
);
}
}Counter.new is a constructor tear-off. Riverpod calls it whenever it needs a fresh instance, so you never call Counter() yourself.
Two ways to read one provider
The same provider has two faces, and you pick one by what you ask for.
| Expression | Returns | Use it to |
|---|---|---|
| `ref.watch(counterProvider)` | The current state (`int`) | Display state and rebuild when it changes |
| `ref.read(counterProvider.notifier)` | The `Counter` instance | Call methods such as `increment()` |
Reading .notifier never subscribes the widget to state changes. That is why ref.read(counterProvider.notifier) is correct inside onPressed. It runs once per tap and has no reason to rebuild anything.
How build() works
build() is not a constructor. Riverpod calls it to produce the initial state. Two details matter.
First, build() runs again whenever a provider it watched changes. The notifier instance stays the same, and its state is replaced by the new return value.
final startValueProvider = Provider<int>((ref) => 10);
class ResettableCounter extends Notifier<int> {
@override
int build() {
// If startValueProvider changes, build runs again and state resets.
return ref.watch(startValueProvider);
}
void increment() => state++;
}
final resettableCounterProvider =
NotifierProvider<ResettableCounter, int>(ResettableCounter.new);Second, ref is a property of the notifier. You can use it in build() and in your methods. The rule from the previous chapter still applies:
- In
build(), useref.watchso the state reacts to its dependencies. - In methods, use
ref.read, because a method is a one-time action and not a subscription.
Do not initialize state in a field or constructor. The notifier has no ref and no state until Riverpod has called build(). Reading state before that point throws an error.
Immutable updates
Riverpod notifies listeners when a new value is assigned to state and the new value is not equal to the old one. It compares them with ==. For int, state++ works because it assigns a new number. For lists, maps and your own classes, mutating the existing object does nothing visible. The object is the same one, so == says nothing changed, and listeners are not told.
class ItemsNotifier extends Notifier<List<String>> {
@override
List<String> build() => const [];
// Wrong: state.add(item) changes the list but assigns nothing.
void add(String item) {
state = [...state, item];
}
void remove(String item) {
state = [
for (final i in state)
if (i != item) i,
];
}
void clear() => state = const [];
}
final itemsProvider =
NotifierProvider<ItemsNotifier, List<String>>(ItemsNotifier.new);For your own state classes, build a new instance with each change. The Profile class from the select section later in this tutorial does this in its birthday() method.
Keeping logic in the notifier
The notifier is the right place for rules about your state. Widgets call a method and stay free of logic.
class BoundedCounter extends Notifier<int> {
static const max = 5;
@override
int build() => 0;
void increment() {
if (state >= max) return;
state++;
}
void decrement() {
if (state <= 0) return;
state--;
}
}
final boundedCounterProvider =
NotifierProvider<BoundedCounter, int>(BoundedCounter.new);If the limit changes later, you edit one class. Every widget that uses it gets the new behavior.
Lifetime of the state
By default, a NotifierProvider keeps its state for as long as its ProviderContainer lives, even when no widget listens to it. For state that should reset when the user leaves a screen, use the autoDispose variant:
final draftProvider =
NotifierProvider.autoDispose<BoundedCounter, int>(BoundedCounter.new);When the last listener is removed, Riverpod drops the notifier and its state. The next read calls build() again and starts fresh. The lifecycle chapter covers this in detail.
Testing a Notifier
Because state lives in a container, you can test a notifier with no widgets.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('BoundedCounter stops at its maximum', () {
final container = ProviderContainer();
addTearDown(container.dispose);
final notifier = container.read(boundedCounterProvider.notifier);
for (var i = 0; i < 10; i++) {
notifier.increment();
}
expect(container.read(boundedCounterProvider), BoundedCounter.max);
});
}addTearDown(container.dispose) releases the container after the test so state does not leak into the next one.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| UI does not update after a change | You mutated `state` in place | Assign a new object to `state` |
| Exception about reading `state` or `ref` too early | Used them in a field initializer or constructor | Move the logic into `build()` |
| Widget rebuilds on every tap for no reason | Used `ref.watch(provider.notifier)` | Use `ref.read(provider.notifier)` in callbacks |
| State resets unexpectedly | `build()` watches a provider that changed | Watch less, or use `ref.read` for values that must not reset state |
| Counter resets when you leave a screen | Provider uses `autoDispose` | Remove `autoDispose` if the state must survive |
Exercise
A Notifier<List<String>> has this method, and the UI never updates after calling it. What is wrong, and how do you fix it?
void add(String item) {
state.add(item);
}
Show answer
The method mutates the existing list and never assigns to state. The list is the same object, so Riverpod sees no change and notifies no listeners. Fix it by assigning a new list: state = [...state, item];.
Exercise
In a ConsumerWidget, you want a button to call reset() on Counter, and a Text to show the count. Which two expressions do you use, and where does each go?
Show answer
Use ref.watch(counterProvider) in build() to get the count for the Text, so the widget rebuilds when the count changes. Use ref.read(counterProvider.notifier).reset() inside the button's onPressed callback, because it is a one-time action that should not subscribe the widget to anything.