Home > Enterprise >  Flutter: How to handle "The default value of an optional parameter must be constant"
Flutter: How to handle "The default value of an optional parameter must be constant"

Time:11-14

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!

CodePudding user response:

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.

  • Related