Should you use "extends" or "with" keyword for ChangeNotifier? - Flutter
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:
- Dart: What are mixins?
- Dart for Flutter : Mixins in Dart
extends
is used to inherit a classwith
is used to use class as a mixin
Refer here to understand difference between mixin and inheritence: https://stackoverflow.com/a/860312/10471480
Refering to ChangeNotifier, the docs says
A class that can be extended or mixed in that provides a change notification API using VoidCallback for notifications.
Hence you can inherit it as well as use it as a mixin