问题描述
我已经看到了几个使用'extends'和'with'关键字扩展ChangeNotifier的模型的示例.我不确定有什么区别.
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?
推荐答案
您可以使用extends
(继承)或with
(作为混合).两种方式都可以让您访问ChangeNotifier
中的notifyListeners()
方法.
You can use either extends
(to inherit) or with
(as a mixin). Both ways give you access to the notifyListeners()
method in ChangeNotifier
.
扩展ChangeNotifier
表示ChangeNotifier
是超类.
class MyModel extends ChangeNotifier {
String someValue = 'Hello';
void doSomething(String value) {
someValue = value;
notifyListeners();
}
}
如果您的模型类已经在扩展另一个类,则不能扩展ChangeNotifier
,因为Dart不允许多重继承.在这种情况下,您必须使用mixin.
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允许您使用mixin类(即notifyListeners()
)的具体方法.
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();
}
}
因此,即使您的模型已经从另一个类扩展了,您仍然可以混入" ChangeNotifier
.
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();
}
}
这里有一些关于mixin的好读物:
Here are some good reads about mixins:
- Dart: What are mixins?
- Dart for Flutter : Mixins in Dart
这篇关于您是否应该使用“扩展"或“具有"关键字是否为ChangeNotifier? -颤振的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!