[英]Dart class optional constructor parameter with default value leads to error
I'm new to Dart and coming from TypeScript I'm struggling to wrap my head around the following error:我是 Dart 的新手并且来自 TypeScript 我正在努力解决以下错误:
The default value of an optional parameter must be constant.可选参数的默认值必须是常量。
For this code:对于此代码:
class Counter {
int base;
List<dynamic> bonus;
Counter({this.base = 0, this.bonus = []}); // Error here
// omitted counter methods
}
class OffensiveAttributes {
Counter oneHanded;
OffensiveAttributes(
{this.oneHanded = Counter(base: 0)}); // And error here
}
What I am trying to achieve is when a new OffensiveAttributes
instance is created, you should be able to have base
set to 2
for example.我想要实现的是,当创建一个新的OffensiveAttributes
实例时,您应该能够将base
设置为2
例如。 Of course I could do this:我当然可以这样做:
Counter oneHanded = Counter(base: 0);
OffensiveAttributes(
{this.oneHanded});
But if oneHanded
isn't passed in when the instance is created, I end up with a value of null
which I don't want.但是如果在创建实例时没有传入oneHanded
,我最终会得到一个我不想要的null
值。
If I try adding const
and final
in the Counter
I get stuck when I need to change the base
value using add
or subtract
methods for example.如果我尝试在Counter
添加const
和final
,当我需要使用add
或subtract
更改base
值时,我会卡住。
What is the correct way of doing this?这样做的正确方法是什么?
Here you need to pass const [] as given below在这里,您需要传递如下所示的 const []
class Counter {
int base;
List<dynamic> bonus;
Counter({this.base = 0, this.bonus = const[]});
// omitted counter methods
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.