1

I want to map a List of Strings to a List of DropdownMenuItems in the Widget constructor. The parent widget passes a List of Strings to the child widget. The child widget must map this List of Strings to a List of DropdownMenuItems. I want to do that in the constructor while keeping the constructor "const". Is that possible? There is a "initState" method for the statefull widgets but I can't find a similar method for the stateless widgets

const SelectableEntry({
  Key? key,
  required this.dropdownList,
})  : mappedList =
          const dropdownList.map((string entry) => DropdownMenuItem<String>(
                value: entry,
                child: Text(entry),
              )).toList(),
      super(key: key);

final List<String> dropdownList;
final List<DropdownMenuItem<String>> mappedList;

@override

...
Gipfeli
  • 197
  • 3
  • 8

1 Answers1

0

If you don't need mappedList to be mutable (and I suppose you don't, as you would lose the changes in mappedList in each rebuild if you're not placing it in the State of a StatefulWidget) you can make the mappedList a getter:

List<DropdownMenuItem<String>> get mappedList => dropdownList
   .map(
     (entry) => DropdownMenuItem<String>(
       value: entry,
       child: Text(entry),
     ),
   )
   .toList();
Albert221
  • 5,223
  • 5
  • 25
  • 41