[英]Assigning subclass to a factory constructor in Dart
Flutter 中的Key
class 有一個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>;
稱為重定向工廠構造函數。 它們並不為人所知(即使在 Dart 和 Flutter 團隊中),因為它們沒有在 Dart 語言之旅中提及,但在Dart 語言規范中(從版本 2.10 開始)第 10.6.2 節中提到了它們:
重定向工廠構造函數指定調用另一個 class 的構造函數,無論何時調用重定向構造函數都會使用該構造函數。
您嘗試使用它們:
const factory Foo(int i) = Bar; // Error
不起作用有兩個原因:
Foo
工廠構造函數聲明為const
,但默認的Bar
構造函數不是const
。 從Foo
工廠構造函數中刪除const
或使Bar
默認構造函數為const
(這也需要使Foo.empty
構造函數為const
)。=
的重定向工廠構造函數時,您沒有機會指定如何傳遞 arguments。這是因為重定向工廠構造函數要求兩個構造函數具有相同的參數。 從Foo
工廠構造函數中刪除未使用的參數,或者使Bar
的構造函數也采用int
參數。您應該注意從 static 分析中得到的錯誤; 他們解釋了以上兩個問題。 在 DartPad 中,我得到:
常量重定向構造函數不能重定向到非常量構造函數。
和
重定向的構造函數“Bar Function()”具有與“Foo Function(int)”不兼容的參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.