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/