我在读一堂课,就像这样:

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

如果这有点难理解,让我们看一下下面的示例

我们有下面的图表

Classes

因为黄色方块指的是行走的能力 蓝色正方形.如上图所示

这里我们有一个叫做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.
}

Dart相关问答推荐

Dart 包对 git repo 子目录的依赖

在Flutter中解析 JSON 到 Map

如何在 Dart 中创建一个空 Set

Dart 中使用 ifAbsent 的 Map Update 方法

Dart - 一个 dart 项目如何在不使用 pub 的情况下从另一个 dart 项目导入代码?

Flutter-创建一个倒计时(countdown)小部件

如何在 GridView (Flutter) 中进行分页

如何在Flatter中的屏幕中心创建选项卡栏?

如何在Flatter dart中使用相同的元素初始化列表?

在向下滚动时隐藏底部导航栏,反之亦然

Flutter 错误:The _ScaffoldLayout custom multichild layout delegate forgot to lay out the following child

Expansion Panel底部溢出

如何在dart中的多个文件中编写多个单元测试?

对该常量表达式的求值会抛出一个表达式

Flutter 构建失败. Android 依赖 'androidx.core:core' 的编译(1.0.0)和运行时(1.0.1)类路径有不同的版本

是什么使它成为 Dart 中的固定长度列表?

什么是健全的编程语言?

pub 依赖和 dev_dependencies 有什么区别?

Dart,对泛型的限制?

如何在 Dart 中创建私有变量?