【发布时间】:2020-11-17 09:11:55
【问题描述】:
根据我的以下代码,我希望有一个Hero 类的构造函数,它将Stats 类作为具有可选参数 strong>基于其构造函数的默认值 (通过可选的命名参数将其健康和攻击字段设置为 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();
}
以下代码有效,但它没有 stats 作为可选参数:
class Hero {
Hero(this.name);
String name;
Stats stats = Stats();
}
【问题讨论】:
标签: dart constructor optional-parameters