37

Is it possible to assign a constant value to an optional parameter of datatype List while defining a constructor. for example,

`class sample{
  final int x;
  final List<String> y;
  sample({this.x = 0; this.y = ["y","y","y","y"]});
 }`

the above code throws an error focused at y assignment saying Default values of an optional parameter must be constant

what is the reason for this error? how else can I assign a default value to the List?

Naveen
  • 1,363
  • 7
  • 17
  • 28

2 Answers2

78

Default values currently need to be const. This might change in the future.

If your default value can be const, adding const would be enough

class sample{
  final int x;
  final List<String> y;
  sample({this.x = 0, this.y = const ["y","y","y","y"]});
}

Dart usually just assumes const when const is required, but for default values this was omitted to not break existing code in case the constraint is actually removed.

If you want a default value that can't be const because it's calculated at runtime you can set it in the initializer list

class sample{
  final int x;
  final List<String> y;
  sample({this.x = 0; List<String> y}) : y = y ?? ["y","y","y","y"];
}
sadat
  • 4,004
  • 2
  • 29
  • 49
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    what if the list was in a separate file, then how will we assign this.y = ? – Jag99 Aug 27 '20 at 05:33
  • 1
    @Gunter Zochbauer - I am facing the same issue, Jag99 has. Kindly share your suggestion, if you have. Thanks. – Kamlesh Jun 28 '21 at 05:04
  • Sorry, no idea what the problem is. If it's in another file the file needs to be imported and in the other file it needs to be public so it can be accessed from the importing file. I'd suggest you create a new question with all the information necessary to reproduce. – Günter Zöchbauer Jun 28 '21 at 07:13
1

Very old question, but as it can still be found with Google, people like me can still find it. Flutter now has a new constructor for the List class to do just this:

final List<String> y = List.filled(4, 'y');

This will create a List with four elements, all set to a value of 'y'.

ehusmann
  • 37
  • 8