3

I have a simple class like this:

class Restaurant{
  final String id;
  final String name;
  List<Serving> servingList;

  Restaurant({
    required this.id,
    required this.name,
    this.servingList = [], // ERROR
  });
}

By default I want an empty List for servingList and add Objects to this List later. But I get the error The default value of an optional parameter must be constant. What do I need to do?

I appreciate every help, thanks!

Dalon
  • 566
  • 8
  • 26
  • I think the proper answer should be this: https://stackoverflow.com/questions/66504939/dart-how-to-create-an-empty-list-as-a-default-parameter – rocotocloc Aug 09 '23 at 08:40

1 Answers1

11

Actually the answer is within the error. The default value should be constant.

    class Restaurant{
  final String id;
  final String name;
  List<Serving> servingList;

  Restaurant({
    required this.id,
    required this.name,
    this.servingList = const [], // ERROR
  });
}

You need to add "const" keyword before the square brackets.

TolgaT
  • 175
  • 2
  • 7
  • 3
    But adding const to the empty list will make it an Unmmodifiable list, this restricts you from making changes to the list because it has been marked as const. How do you solve this issue? – davidn Jan 19 '22 at 18:19
  • 2
    The fact that is is unanswered is appalling. Dart as a language leaves a lot to be desired. – Jason Henriksen Jul 26 '22 at 06:46
  • In the end, you have to do something really dumb if you want a growable-by-default list. Because you are FORCED to have a const optional param, that means you are forced to have a non-growable list, which you'd end up making zero length. You're only option at that point is to provide a constructor body that cleans up the mess: ``` Constructor({ this.myGrowableList = const [], }) { if (myGrowableList.isNotEmpty) { this.myGrowableList = myGrowableList; } else { this.myGrowableList = List.empty(growable: true); } } ``` – Jason Henriksen Jul 26 '22 at 07:00