[英]Assigning subclass to a factory constructor in Dart
The Key
class in Flutter has a factory
constructor which works more like a variable. Flutter 中的Key
class 有一个factory
构造函数,它更像一个变量。
abstract class Key {
const factory Key(String value) = ValueKey<String>;
// ...
}
But when I do something like that, I get an error:但是当我这样做时,我得到一个错误:
class Foo {
Foo.empty();
const factory Foo(int i) = Bar; // Error
}
class Bar extends Foo {
Bar() : super.empty();
}
Actually I didn't quite get what is the use of this factory constructor cum variable.其实我不太明白这个工厂构造函数和变量有什么用。 Can anyone please explain.谁能解释一下。
A constructor like:一个构造函数,如:
const factory Key(String value) = ValueKey<String>;
is called a redirecting factory constructor .称为重定向工厂构造函数。 They're not well-known (even within the Dart and Flutter teams) since they aren't mentioned in the Dart Language Tour , but they're mentioned in the Dart Language Specification in (as of version 2.10) section 10.6.2:它们并不为人所知(即使在 Dart 和 Flutter 团队中),因为它们没有在 Dart 语言之旅中提及,但在Dart 语言规范中(从版本 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.重定向工厂构造函数指定调用另一个 class 的构造函数,无论何时调用重定向构造函数都会使用该构造函数。
Your attempt to use them:您尝试使用它们:
const factory Foo(int i) = Bar; // Error
doesn't work for two reasons:不起作用有两个原因:
Foo
factory constructor as const
, but the default Bar
constructor is not const
.您将Foo
工厂构造函数声明为const
,但默认的Bar
构造函数不是const
。 Either remove const
from the Foo
factory constructor or make the Bar
default constructor const
(which also would require making the Foo.empty
constructor const
).从Foo
工厂构造函数中删除const
或使Bar
默认构造函数为const
(这也需要使Foo.empty
构造函数为const
)。=
, there's no opportunity for you to specify how to pass arguments. That's because a redirecting factory constructor requires that both constructors have the same parameters.请注意,当您使用带有=
的重定向工厂构造函数时,您没有机会指定如何传递 arguments。这是因为重定向工厂构造函数要求两个构造函数具有相同的参数。 Either remove the unused parameter from the Foo
factory constructor or make Bar
's constructor take an int
argument too.从Foo
工厂构造函数中删除未使用的参数,或者使Bar
的构造函数也采用int
参数。You should pay attention to the errors that you get from static analysis;您应该注意从 static 分析中得到的错误; they explain the above two issues.他们解释了以上两个问题。 In DartPad, I get:在 DartPad 中,我得到:
A constant redirecting constructor can't redirect to a non-constant constructor.常量重定向构造函数不能重定向到非常量构造函数。
and和
The redirected constructor 'Bar Function()' has incompatible parameters with 'Foo Function(int)'.重定向的构造函数“Bar Function()”具有与“Foo Function(int)”不兼容的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.