In object-oriented programming languages, a Mixin is a class that contains methods for use by other classes without having to be the parent class of those other classes.
即,mixin 是另外一个普通类,我们可以在不继承这个类的情况下从这个类”借用”方法和变量。
Support for the mixin keyword was introduced in Dart 2.1. Code in earlier releases usually used abstract class instead.
从这个角度来讲,mixin 不过是 abstract class。
Java tries to make up for this by using Interfaces, but that is not as useful or flexible as mixins.
The keyword on is used to restrict our mixin’s use to only classes which either extends or implements the class it is declared on. In order to use the on keyword, you must declare your mixin using the mixin keyword
1 2 3 4 5 6 7
classB{} mixin Y on B { void hi() { print('hi'); } } classQwithY{}
则有如下错误提示:
Error: 'Object' doesn't implement 'B' so it can't be used with 'Y'.
on 关键字限制了 Y 的使用范围:Y 只能用于继承或实现了 B 的类。修复方式是让 Q 继承自 B:
Mixins in Dart work by creating a new class that layers the implementation of the mixin on top of a superclass to create a new class — it is not “on the side” but “on top” of the superclass, so there is no ambiguity in how to resolve lookups. Mixins is not a way to get multiple inheritance in the classical sense. Mixins is a way to abstract and reuse a family of operations and state. It is similar to the reuse you get from extending a class, but it is compatible with single-inheritance because it is linear. StackOverflow
Since each mixin application creates a new class, it also creates a new interface (because all Dart classes also define interfaces). As described, the new class extends the superclass and includes copies of the mixin class members, but it also implements the mixin class interface. In most cases, there is no way to refer to that mixin-application class or its interface; the class for Super with Mixin is just an anonymous superclass of the class declared like class C extends Super with Mixin {}. If you name a mixin application like class CSuper = Super with Mixin {}, then you can refer to the mixin application class and its interface, and it will be a sub-type of both Super and Mixin.
main(List<String> args) { WidgetsFlutterBinding b = WidgetsFlutterBinding(); print('main(): $b'); }
这段代码输出为:
1 2 3 4 5 6 7 8 9
BindingBase.initInstances() GestureBinding.initInstances() Instance of 'WidgetsFlutterBinding' ServicesBinding.initInstances() Instance of 'WidgetsFlutterBinding' SchedulerBinding.initInstances() Instance of 'WidgetsFlutterBinding' PaintingBinding.initInstances() Instance of 'WidgetsFlutterBinding' SemanticsBinding.initInstances() Instance of 'WidgetsFlutterBinding' RendererBinding.initInstances() Instance of 'WidgetsFlutterBinding' WidgetsBinding.initInstances() Instance of 'WidgetsFlutterBinding' main(): Instance of 'WidgetsFlutterBinding'