I have seen several examples of a model extending ChangeNotifier using both 'extends' and 'with' keywords. I am not sure what the difference is.
class myModel extends ChangeNotifier {...} class myModel with ChangeNotifier {...} What is the difference between those two? Which one should I use?
You can use either extends (to inherit) or with (as a mixin). Both ways give you access to the notifyListeners() method in ChangeNotifier.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With