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

Issue

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!

Solution

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.

Answered By – TolgaT

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.