简体   繁体   English

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

[英]Initializing member with constructor in an optional parameter constructor in Dart

Based on my following code, I want to have a constructor of the class Hero that takes a Stats class as an optional parameter that has a default value based on its constructor (the one that set its health and attack fields to 100 and 10 by an optional named parameter) instead of null .根据我的以下代码,我想要一个 class Hero构造函数,它将Stats class 作为可选参数,该参数具有基于其构造函数的默认值(将其健康和攻击字段设置为 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;
}

More things i've tried:我尝试过的更多事情:

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();
}

This following code works but it doesn't have stats as an optional parameter:以下代码有效,但它没有 stats 作为可选参数:

class Hero {
  Hero(this.name);
  String name;
  Stats stats = Stats();
}

(Credits to @jamesdlin for linking to his answer in the comments) (感谢@jamesdlin在评论中链接到他的答案

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:一般来说,如果没有可用的 const 构造函数,您可以改用 null 默认值(或其他适当的标记值),然后稍后设置所需的值:

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.) (请注意,将 null 作为参数显式传递,与直接设置默认值相比,这种方法会做不同的事情。也就是说,使用这种方法的 Foo(bar: null) 会将 bar 初始化为 Bar(),而使用普通方法默认值会将 bar 初始化为 null。然而,在某些情况下,这种方法的行为可能更理想。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM