Flutter: How to handle "The default value of an optional parameter must be constant"
Asked Answered
H

1

8

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!

Hennery answered 13/11, 2021 at 16:11 Comment(1)
I think the proper answer should be this: #66505439Willetta
C
15

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.

Cristiano answered 13/11, 2021 at 16:27 Comment(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?Kathlyn
The fact that is is unanswered is appalling. Dart as a language leaves a lot to be desired.Anaximander
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); } } ```Anaximander

© 2022 - 2024 — McMap. All rights reserved.