7

How can I bind key value array as shown below to flutter dropdownbutton? I want the key to be the drop-down list value and value to be the label.

  final items = {
        '1': 'item 1',
        '2': 'item 2',
        '3': 'item 3',
        '4': 'item 4',
        '5': 'item 5'
      };

2 Answers 2

13

Use this:

DropdownButton<String> button = DropdownButton(
  items: items.entries
      .map<DropdownMenuItem<String>>(
          (MapEntry<String, String> e) => DropdownMenuItem<String>(
                value: e.key,
                child: Text(e.value),
              ))
      .toList(),
  onChanged: (String newKey) {/* todo handle change */},
);
0
4

It's simple, the snippet below show you how to...

final items = { 
      '1': 'item 1',
      '2': 'item 2',
      '3': 'item 3',
      '4': 'item 4',
      '5': 'item 5'
    };

    // your list of DropDownMenuItem
    List< DropdownMenuItem<String>> menuItems = List();

    // loop in the map and getting all the keys
    for(String key in items.keys){
      menuItems.add(
          DropdownMenuItem<String>(
            // items[key] this instruction get the value of the respective key
            child: Text( items[key] ), // the value as text label
            value: key, // the respective key as value
      ) );
    }

//later you will do something like this
DropdownButton<String>(
              items: menuItems,
              onChanged: (value){
                // do your stuffs
              },
            );
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.