gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:57:09 25 4
gpt4 key购买 nike

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 anotherclass 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com