List Comprehension for DropdownButton in Flutter (Dart)

Viewed 191

I am currently learning Flutter and want to create a DropdownButton with the following list:

const List<String> currenciesList = [
  'AUD',
  'BRL',
  'CAD',
  'CNY',
  'EUR',
];

The item attribute of the DropdownButton widget expects a list. Therefore, I want to clean the code by using a list comprehension. I have written the following function to create a DropdownMenuItem depending on the given string:

DropdownMenuItem makeDropdownMenuItem (String currency) {
  DropdownMenuItem item = DropdownMenuItem(
    child: Text(currency),
    value: currency,
  );
  return item;
}

Unfortunately, when I use the list comprehension syntax I found here, I get an error:

child: DropdownButton<String>(
              value: selectedCurrency,
              items: currenciesList.map((currency) => makeDropdownMenuItem(currency)).toList(),
              onChanged: (value) {
                setState(() {
                  selectedCurrency = value;
                });
            },

type 'List<DropdownMenuItem>' is not a subtype of type 'List<DropdownMenuItem>?'

Can anyone help me fixing this please? Thanks a lot!

2 Answers

DropdownMenuItem is a generic class, so you've to specify the actual type explicitly in your makeDropdownMenuItem function:

DropdownMenuItem<String> makeDropdownMenuItem(String currency) {
  final item = DropdownMenuItem(
    child: Text(currency),
    value: currency,
  );
  return item;
}

First of all,

Unfortunately, when I use the list comprehension syntax I found, I get an error:

That's not the new list comprehension. This is:

child: DropdownButton<String>(
  value: selectedCurrency,
  onChanged: (value) => setState(() => selectedCurrency = value),
  items: [
    for (final currency in currenciesList)
      makeDropdownMenuItem(currency)
  ],
)

I find it much cleaner and you can add ifs or nested for loops too.


Then, as @Midhun said, you need to mark your function as returning a DropdownMenuItem<String>. Or, you can continue using your list comprehension:

child: DropdownButton<String>(
  value: selectedCurrency,
  onChanged: (value) => setState(() => selectedCurrency = value),
  items: [
    for (final currency in currenciesList) DropdownMenuItem(
      child: Text(currency),
      value: currency,
    );
  ],
)
Related