根据我的以下代码,我希望有一个Hero
类的构造函数,它将Stats
类作为可选参数,其默认值基于其构造函数(用于设置其健康和攻击字段的那个)可选的命名参数)分别设置为100和10,而不是null 。
void main() {
Hero hero = Hero("Foo");
print('${hero.name} : HP ${hero.stats.health}');
}
class Stats {
Stats({this.health = 100, this.attack = 10});
double health;
double attack;
}
class Hero {
// error: The default value of an optional parameter must be constant
Hero(this.name,[this.stats = Stats()]);
String name;
Stats stats;
}
我尝试过的更多操作:class Hero {
// error: Can't have a const constructor for a class with non-final fields
Hero(this.name,[this.stats = const Stats()]);
String name;
Stats stats;
}
class Hero {
// error: stats initialized as null
Hero(this.name,[this.stats]);
String name;
Stats stats = Stats();
}
以下代码有效,但没有统计信息作为可选参数:class Hero {
Hero(this.name);
String name;
Stats stats = Stats();
}
最佳答案
(在评论中链接至@jamesdlin,从而获得his answer的积分)
In general, if there isn't a const constructor available, you instead can resort to using a null default value (or some other appropriate sentinel value) and then setting the desired value later:
class Foo {
Bar bar;
Foo({Bar bar}) : bar = bar ?? Bar();
}
(Note that explicitly passing null as an argument will do something different with this approach than if you had set the default value directly. That is, Foo(bar: null) with this approach will initialize bar to Bar(), whereas with a normal default value it would initialize bar to null. In some cases, however, this approach's behavior might be more desirable.)
关于dart - 在Dart中的可选参数构造函数中使用构造函数初始化成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63125472/