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

烂漫一生 提交于 2020-01-02 15:54:30

问题


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?


回答1:


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



回答2:


extends is used to inherit a class
with 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



来源:https://stackoverflow.com/questions/56680226/should-you-use-extends-or-with-keyword-for-changenotifier-flutter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!