ChangeNotifier
- Flutter course
- Intermediate
- Lesson 7/99
- 4 min
Build a listenable state class with ChangeNotifier.
ChangeNotifier
ChangeNotifier is a class that notifies its listeners when it changes. You extend it for your state model and call notifyListeners() on change.
class CounterModel extends ChangeNotifier {
int value = 0;
void increment() {
value++;
notifyListeners();
}
}Listening widgets rebuild automatically.
Model class
A model class holds the state and the methods that change it. When you extend ChangeNotifier, calling notifyListeners() on every change is enough; the framework handles the rest.
class CounterModel extends ChangeNotifier {
int value = 0;
void increment() {
value++;
notifyListeners();
}
}The model can also live in a separate file.
Practice Build a ChangeNotifier model
Make SayacModeli extend ChangeNotifier. deger starts at 0. The artir method increments deger, calls notifyListeners(), and prints print('artirildi: $deger'). In main, create the model and call artir.
Starter code
import 'package:flutter/material.dart';
// SayacModeli, ChangeNotifier'dan türetilsin
class SayacModeli {
int deger = 0;
void artir() {
deger++;
// notifyListeners çağrısı ekle
print('artirildi: $deger');
}
}
void main() {
final model = SayacModeli();
model.artir();
}Sample solution
import 'package:flutter/material.dart';
class SayacModeli extends ChangeNotifier {
int deger = 0;
void artir() {
deger++;
notifyListeners();
print('artirildi: $deger');
}
}
void main() {
final model = SayacModeli();
model.artir();
}Expected output
artirildi: 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method is called to notify listeners in ChangeNotifier?
- rebuild()
- notifyListeners() Correct answer
- update()
- setState()
Explanation: When state changes in a ChangeNotifier, notifyListeners() is called; this informs listening widgets to rebuild.
2 Add the notifyListeners call
class SayacModeli extends ChangeNotifier {
int deger = 0;
void artir() {
deger++;
____;
}
}
class SayacModeli extends ChangeNotifier {
int deger = 0;
void artir() {
deger++;
notifyListeners();
}
}
Explanation: After deger changes, notifyListeners() is called in a ChangeNotifier; this informs listening widgets.
3 ChangeNotifier parts
| Term | Meaning |
|---|---|
ChangeNotifier |
Base class that notifies listeners |
notifyListeners |
Tells listeners about change |
extends ChangeNotifier |
Making the model listenable |
model |
Class holding state and methods |