StateNotifier
- Flutter course
- Advanced
- Lesson 1/69
- 4 min
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];
}Practice 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.
Starter code
import 'package:flutter_riverpod/flutter_riverpod.dart';
// CounterNotifier sınıfını buraya yaz
// int state tutsun, increment ile 1 artırsın
void main() {
// örnek oluştur, iki kez artır, yazdır
}Sample 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);
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is the state updated with StateNotifier?
- state = newValue Correct answer
- state.update(newValue)
- setState(newValue)
- notify(newValue)
Explanation: In StateNotifier the state is a field, so you assign to it directly; there are no update, setState, or notify methods.
2 Provide the initial state
class CounterNotifier extends StateNotifier<int> {
CounterNotifier() : super(____);
void increment() => state = state + 1;
}
class CounterNotifier extends StateNotifier<int> {
CounterNotifier() : super(0);
void increment() => state = state + 1;
}
Explanation: The super call of StateNotifier takes the initial state value; here the counter starts at 0.
3 StateNotifier parts
| Term | Meaning |
|---|---|
StateNotifier<int> |
Holds state of type int |
super(0) |
Initial value 0 |
state = ... |
Updates the state |
extends StateNotifier |
Extending the class |