【问题标题】:Initializing member with constructor in an optional parameter constructor in Dart在 Dart 的可选参数构造函数中使用构造函数初始化成员
【发布时间】: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


【解决方案1】:

(感谢 @jamesdlin 在 cmets 中链接到 his answer

一般来说,如果没有可用的 const 构造函数,则改为 可以求助于使用空默认值(或其他一些适当的 哨兵值),然后设置所需的值:

class Foo {
  Bar bar;

  Foo({Bar bar}) : bar = bar ?? Bar();
}

(请注意,显式传递 null 作为参数会做一些事情 这种方法与设置默认值不同 直接地。也就是说,使用这种方法的 Foo(bar: null) 将初始化 bar 到 Bar(),而使用正常的默认值,它将初始化 栏为空。然而,在某些情况下,这种方法的行为可能是 更可取。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 2011-05-02
    相关资源
    最近更新 更多