How to set Initialize of List value on class

I want to receive the list variable as an option.
So, I tried to create class and bring it up as below, but there is an “The default value of an optional parameter must be constant.” error in the constructor function.

I understood that the initialize of the List value can be set as below.
this.items = [];
But not worked.
Can you let me know to set it?

this.items = List.generate(1, (index) => index),

class Item {
Item({
required this.expandedValue,
required this.headerValue,
this.isExpanded = false,
this.items = List.generate(1, (index) => index),
});

String expandedValue;
String headerValue;
bool isExpanded;
List items;
}

Change the line this.items = List.generate(1, (index) => index), to this.items = const [0],.

Alternatively, if you need to use default values that cannot be constant, you can use the factory keyword like this:

class Item {
  Item({
    required this.expandedValue,
    required this.headerValue,
    required this.isExpanded,
    required this.items
  });
  
  factory Item.usingFactory({
    required String expandedValue,
    required String headerValue,
    bool isExpanded = false,
    List? items,
  }) {
    return Item(
      expandedValue: expandedValue,
      headerValue: headerValue,
      isExpanded: isExpanded,
      items: items ?? List.generate(1, (index) => index),
    );
  }

  String expandedValue;
  String headerValue;
  bool isExpanded;
  List items;
}
1 Like