我在读一堂课,就像这样:
class SplashScreenState extends State<SplashScreen>
with SingleTickerProviderStateMixin {
...
...
}
我只是想知道with关键字在这个上下文中指的是什么,我们为什么要使用它?
我在读一堂课,就像这样:
class SplashScreenState extends State<SplashScreen>
with SingleTickerProviderStateMixin {
...
...
}
我只是想知道with关键字在这个上下文中指的是什么,我们为什么要使用它?
我从here人那里得到了答案.
我会把它拆开的
我要找的概念叫做Mixins
那么什么是混合物?
Mixins are a way of reusing a class’s code in multiple class hierarchies, In other words when we need a functionality and we cannot implement it in one of a super class , or it does not make sense to do so
如果这有点难理解,让我们看一下下面的示例
我们有下面的图表
因为黄色方块指的是行走的能力 蓝色正方形.如上图所示
这里我们有一个叫做Animal的超类,它有三个子类(哺乳动物、鸟类和鱼类)
有些动物有共同的行为:cat 和鸽子都会走路,但cat 不会飞.
现在我们来看一下with的用法
让我们定义Walker类
class Walker {
void walk() {
print("I'm walking");
}
}
为了解决上述问题,我们使用了Mixin
class Cat extends Mammal with Walker {}
class Dove extends Bird with Walker, Flyer {}
现在如果我们打电话给
main(List<String> arguments) {
Cat cat = Cat();
Dove dove = Dove();
// A cat can walk.
cat.walk();
// A dove can walk and fly.
dove.walk();
dove.fly();
// A normal cat cannot fly.
// cat.fly(); // Uncommenting this does not compile.
}