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'
};
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 */},
);
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
},
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With