是否可以对类的静态属性进行非延迟初始化?

Dmi*_*pka 5 static lazy-initialization dart

我想要实现的目标的一个简短示例:

class Country {
  final int id;
  final String name;

  static List<Country> values = new List<Country>();

  static final Country US = new Country._create(1, 'United States');
  static final Country UK = new Country._create(2, 'United Kingdom');

  Country._create(this.id, this.name) {
    values.add(this);
  }
}
Run Code Online (Sandbox Code Playgroud)

我有一个带有私有命名构造函数的 Country 类。我想创建一组静态国家/地区常量和所有可用国家/地区的列表。

这就是问题所在:

void main() {
  print('Countries:');
  for (Country country in Country.values) {
    print(country.name);
  }
}
Run Code Online (Sandbox Code Playgroud)

由于静态成员的延迟初始化,我的列表是空的。然而:

void main() {

  print('US id is: ${Country.US.id}');

  print('Countries:');
  for (Country country in Country.values) {
    print(country.name);
  }
}
Run Code Online (Sandbox Code Playgroud)

仅当我在代码中引用 US 常量时,它才会添加到列表中。

在我的静态国家/地区列表中填充国家/地区而无需一一添加的最简单方法是什么?

Gün*_*uer 1

只需使用列表文字,而不是将其添加到构造函数中:

class Country {
  final int id;
  final String name;

  static List<Country> values = <Country>[US, UK];

  static const Country US = new Country._create(1, 'United States');
  static const Country UK = new Country._create(2, 'United Kingdom');

  Country._create(this.id, this.name);
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用这种方式const来提高效率

class Country {
  final int id;
  final String name;

  static const List<Country> values = const <Country>[US, UK];

  static const Country US = const Country._create(1, 'United States');
  static const Country UK = const Country._create(2, 'United Kingdom');

  const Country._create(this.id, this.name);
}
Run Code Online (Sandbox Code Playgroud)