如何将如下所示的键值数组绑定到flutter dropdownbutton?我希望键是下拉列表值,而值是标签。
final items = {
'1': 'item 1',
'2': 'item 2',
'3': 'item 3',
'4': 'item 4',
'5': 'item 5'
};
答案 0 :(得分:5)
使用此:
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 */},
);
答案 1 :(得分:1)
很简单,下面的代码段向您展示了如何...
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
},
);