Flutter
StateNotifier
Manage immutable state with StateNotifier.
What is StateNotifier?
StateNotifier is a class that holds a single immutable state and manages changes to it. To update the state you assign state = newState, which replaces the old state with a new one. Used with Riverpod, listening widgets rebuild automatically whenever the state changes.
class CounterNotifier extends StateNotifier<int> {
CounterNotifier() : super(0);
void increment() => state = state + 1;
}
The immutable state principle
Because the state is immutable, you cannot assign directly with state.field = value; you must always assign a brand new object. This makes it easier to track and undo changes without corrupting previous state. For lists, building a new one with [...state, item] is a common pattern.
class TodoNotifier extends StateNotifier<List<String>> {
TodoNotifier() : super([]);
void add(String todo) => state = [...state, todo];
}
Exercise Write a CounterNotifier class
Write a StateNotifier class named CounterNotifier that holds an int. Initialize it with super(0). Its increment method should increase state by 1. In main, create an instance, call increment twice, and print state.
Show example solution
import 'package:flutter_riverpod/flutter_riverpod.dart';
class CounterNotifier extends StateNotifier<int> {
CounterNotifier() : super(0);
void increment() => state = state + 1;
}
void main() {
final counter = CounterNotifier();
counter.increment();
counter.increment();
print(counter.state);
}
Test yourself
-
How is the state updated with StateNotifier?
- state = newValue
- state.update(newValue)
- setState(newValue)
- notify(newValue)
Show answer
state = newValue — In StateNotifier the state is a field, so you assign to it directly; there are no update, setState, or notify methods.
-
Provide the initial state
class CounterNotifier extends StateNotifier<int> {
CounterNotifier() : super(____);
void increment() => state = state + 1;
}
Show answer
class CounterNotifier extends StateNotifier<int> {
CounterNotifier() : super(0);
void increment() => state = state + 1;
}
-
StateNotifier parts
- StateNotifier<int>
- Holds state of type int
- super(0)
- Initial value 0
- state = ...
- Updates the state
- extends StateNotifier
- Extending the class
Next lesson: StateNotifierProvider