简体   繁体   English

Dart 类可选构造函数参数默认值导致错误

[英]Dart class optional constructor parameter with default value leads to error

I'm new to Dart and coming from TypeScript I'm struggling to wrap my head around the following error:我是 Dart 的新手并且来自 TypeScript 我正在努力解决以下错误:

The default value of an optional parameter must be constant.可选参数的默认值必须是常量。

For this code:对于此代码:

class Counter {
  int base;
  List<dynamic> bonus;

  Counter({this.base = 0, this.bonus = []}); // Error here

  // omitted counter methods
}

class OffensiveAttributes {
  Counter oneHanded;

  OffensiveAttributes(
      {this.oneHanded = Counter(base: 0)}); // And error here
}

What I am trying to achieve is when a new OffensiveAttributes instance is created, you should be able to have base set to 2 for example.我想要实现的是,当创建一个新的OffensiveAttributes实例时,您应该能够将base设置为2例如。 Of course I could do this:我当然可以这样做:

Counter oneHanded = Counter(base: 0);

OffensiveAttributes(
      {this.oneHanded});

But if oneHanded isn't passed in when the instance is created, I end up with a value of null which I don't want.但是如果在创建实例时没有传入oneHanded ,我最终会得到一个我不想要的null值。

If I try adding const and final in the Counter I get stuck when I need to change the base value using add or subtract methods for example.如果我尝试在Counter添加constfinal ,当我需要使用addsubtract更改base值时,我会卡住。

What is the correct way of doing this?这样做的正确方法是什么?

Here you need to pass const [] as given below在这里,您需要传递如下所示的 const []

class Counter {
  int base;
  List<dynamic> bonus;

  Counter({this.base = 0, this.bonus = const[]}); 

  // omitted counter methods
}

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

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