[英]How to define value in the constructor to pass to the super constructor in Dart?
我有一些代碼,例如:
class P extends StatelessWidget {
final List<int> l;
final int x;
const P({
required this.l,
required this.x,
Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
// TODO: implement build
throw UnimplementedError();
}
}
class A extends P {
A({required int x, Key? key}) : super(l: [], x: x, key: key);
}
我想做的是將A
class 構造函數更改為:
A({required int x, Key? key}) {
final int a = 3;
final int b = 5;
final int c = -1;
}: super(l: [a, b, c], x: x, key: key);
有沒有辦法用 Dart 實現類似的目標?
更新
Yeasin 建議的版本適用於我示例中的簡單案例,但如果案例更復雜,例如:
class A extends P {
A({
required int x,
Key? key,
ChangeNotifierProvider<UIComponentState> a = ChangeNotifierProvider<UIComponentState>((ref) => UIComponentState()),
ChangeNotifierProvider<UIComponentState> b = ChangeNotifierProvider<UIComponentState>((ref) => UIComponentState()),
ChangeNotifierProvider<UIComponentState> c = ChangeNotifierProvider<UIComponentState>((ref) => UIComponentState()),
}) : super(l: [a, b, c], l2: [a, b, c], x: x, key: key);
}
當我得到錯誤時:
可選參數的默認值必須是常量。
除非您打算稍后使用a
、 b
和c
,否則為它們添加變量並不是很有用,尤其是當它們是常量時。 因此,您可以使用
super(l: [3, 5, -1], x: x, key: key)
直接,或者如果你真的想要 label 值,你可以添加命名常量或static
變量。
更一般地說,如果您希望變量存儲中間計算,那么您最好使用factory
構造函數(或static
方法)來創建 class 的實例:
class A extends P {
A._({required List<int> l, required int x, required Key? key})
: super(l: l, x: x, key: key);
factory A({required int x, Key? key}) {
var a = 3;
var b = 5;
var c = -1;
return A._(l: [3, 5, -1], x: x, key: key);
}
}
盡管請注意,如果您稍后將 class 用作基礎 class ,那么這樣做會使您的 class 更難衍生。
你可以做這樣的事情
class A extends P {
A({
required int x,
Key? key,
int a = -1,
int b = 5,
int c = -1,
}) : super(l: [a, b, c], x: x, key: key);
}
或嘗試
class A extends P {
A({
required int x,
Key? key,
final int? a,
final int? b,
final int? c,
}) : super(l: [a ?? 3, b ?? 5, c ?? -1], x: x, key: key);
}
命名構造函數參數是可選的。 更多關於using-constructors
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.