You can use either extends
(to inherit) or with
(as a mixin). Both ways give you access to the notifyListeners()
method in ChangeNotifier
.
Inheritance
Extending ChangeNotifier
means that ChangeNotifier
is the super class.
class MyModel extends ChangeNotifier {
String someValue = 'Hello';
void doSomething(String value) {
someValue = value;
notifyListeners();
}
}
If your model class is already extending another class, then you can't extend ChangeNotifier
because Dart does not allow multiple inheritance. In this case you must use a mixin.
Mixin
A mixin allows you to use the concrete methods of the mixin class (ie, notifyListeners()
).
class MyModel with ChangeNotifier {
String someValue = 'Hello';
void doSomething(String value) {
someValue = value;
notifyListeners();
}
}
So even if your model already extends from another class, you can still "mix in" ChangeNotifier
.
class MyModel extends SomeOtherClass with ChangeNotifier {
String someValue = 'Hello';
void doSomething(String value) {
someValue = value;
notifyListeners();
}
}
Here are some good reads about mixins: