Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter dropdownbutton bind key value array

Tags:

flutter

dart

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'
      };
like image 797
Huzzi Avatar asked Jan 18 '19 20:01

Huzzi


2 Answers

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 */},
);
like image 90
Richard Heap Avatar answered Sep 19 '22 05:09

Richard Heap


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
              },
            );
like image 42
Marcos Boaventura Avatar answered Sep 19 '22 05:09

Marcos Boaventura