Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you use "extends" or "with" keyword for ChangeNotifier? - Flutter

Tags:

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?

like image 212
Gary AP Avatar asked Jun 20 '19 06:06

Gary AP


1 Answers

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
like image 112
Suragch Avatar answered May 29 '23 18:05

Suragch