dart - 在Dart中的可选参数构造函数中使用构造函数初始化成员

标签 dart constructor optional-parameters

根据我的以下代码,我希望有一个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/

相关文章:

java - 我可以将循环作为参数传递给构造函数吗

android - 为什么 ListView 不显示用户输入的文本

dart - 在 Dart 中将 ByteBuffer 快速复制到 ByteBuffer

c++ - fstream 初始化为一个类

Fortran 90 存在可选参数

vb.net - 声明可选字符串数组参数的语法

java - 在运行时传递可选的未知参数

flutter - 如何读取注释字段及其值(代码生成)

flutter - 如何显示 double 到 2 个小数点?

c++ - 构造函数中的构造函数中的绑定(bind)