0

I'm new to Dart and coming from TypeScript I'm struggling to wrap my head around the following error:

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. 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.

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.

What is the correct way of doing this?

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • Does this answer your question? [Default values of an optional parameter must be constant](https://stackoverflow.com/questions/51907159/default-values-of-an-optional-parameter-must-be-constant) – Mattia Sep 19 '20 at 16:14
  • @Mattia No, I looked at that question but I still don't understand how to change my code. – Chrillewoodz Sep 19 '20 at 16:22
  • 2
    See https://stackoverflow.com/a/56489812/. – jamesdlin Sep 19 '20 at 19:42
  • @jamesdlin Thanks! That solved it. Also read https://medium.com/flutter-community/deconstructing-dart-constructors-e3b553f583ef which gave me some insight in what the different syntaxes are called and how they're used. – Chrillewoodz Sep 20 '20 at 06:41

1 Answers1

0

Here you need to pass const [] as given below

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

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

  // omitted counter methods
}
Khadga shrestha
  • 1,120
  • 6
  • 11