Flutter: Default assignment of List parameter in a constructor

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"];
}

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

Tags:

Dart

Flutter