flutter - 将子类分配给 Dart 中的工厂构造函数

标签 flutter dart

Flutter 中的 Key 类有一个 factory 构造函数,它的工作方式更像一个变量。

abstract class Key {
  const factory Key(String value) = ValueKey<String>;

  // ...
}

但是当我这样做时,我得到一个错误:

class Foo {
  Foo.empty();
  const factory Foo(int i) = Bar; // Error
}

class Bar extends Foo {
  Bar() : super.empty();
}

其实我不太明白这个工厂构造函数和变量有什​​么用。谁能解释一下。

最佳答案

构造函数如:

const factory Key(String value) = ValueKey<String>;

被称为重定向工厂构造函数。自 they aren't mentioned in the Dart Language Tour 以来,它们并不出名(即使在 Dart 和 Flutter 团队中也是如此) ,但在 the Dart Language Specification 中提到了它们在(自 2.10 版起)第 10.6.2 节中:

A redirecting factory constructor specifies a call to a constructor of another class that is to be used whenever the redirecting constructor is called.

您尝试使用它们:

const factory Foo(int i) = Bar; // Error

不工作有两个原因:

  • 您将 Foo 工厂构造函数声明为 const,但默认的 Bar 构造函数不是 const。从 Foo 工厂构造函数中删除 const 或使 Bar 默认构造函数 const (这也需要使Foo.empty 构造函数 const).
  • 请注意,当您使用带有 = 的重定向工厂构造函数时,您没有机会指定如何传递参数。那是因为重定向工厂构造函数要求两个构造函数具有相同的参数。从 Foo 工厂构造函数中删除未使用的参数,或者使 Bar 的构造函数也采用 int 参数。

您应该注意从静态分析中得到的错误;他们解释了以上两个问题。在 DartPad 中,我得到:

A constant redirecting constructor can't redirect to a non-constant constructor.

The redirected constructor 'Bar Function()' has incompatible parameters with 'Foo Function(int)'.

关于flutter - 将子类分配给 Dart 中的工厂构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69511105/

相关文章:

Flutter - 颜色名称字符串到 Material 颜色

flutter - 避免在生产代码中调用 `print`。 (文档)

dart - 如何使用 Dart 检测 Flutter 字符串中的表情符号?

firebase - 如何从cloud firestore获取数据,其中user.uid等于flutter中的文档ID?

android - Flutter 应用程序无法以 Debug模式启动

dart - 如何将多个 entry_points 传递给 pubspec.yaml 中的聚合物转换器?

flutter - Excel flutter 按列读取数据

dart - Flutter - 任何人都有一个 Flow 示例来有条件地左右对齐包装?

Flutter:如何获得高精度定位?

dart - 使用clone()-Node类方法-性能良好吗?