i was wondering if you use a DropDownMenu in Flutter there is a possibility to get different values.
For Example: You have the items ['item1','item2','item3','item4','item5'] then you use a DropDownButton with these items. But for every single item there should be passed a different value so i can work with that later.
So that item1 = 90, item2 = 180, item3 = 270 and so on. If item1 is selected it should be displayed to the user like that and the app gets the value 90 for example where it can work with later.
I hope you get what i mean and can help me a litte bit.
CodePudding user response:
You can create a map and use it's key for DropDownMenu, While showing use key to show value like
String? dropdownValue;
Map<String, int> dataset = {
"item1": 90,
"item2": 180,
"item3": 270,
};
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
DropdownButtonHideUnderline(
child: DropdownButton<String>(
value: dropdownValue,
focusColor: Colors.white,
items: dataset.keys.map((String value) {
return DropdownMenuItem(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (v) {
setState(() {
dropdownValue = v;
});
},
),
),
Text(
dropdownValue == null
? "Select Item "
: dataset[dropdownValue!].toString(),
),
CodePudding user response:
There are a lot of ways to do so.
1- Through key-value pairs.
Get your sample for example:
items[{'name':'item1','value':'90'},{'name':'item2','value':'180'},{'name':'item3','value':'270'},{'name':'item4','value':'360'}];
(presumably they are a 360 degree angels :-))
Then you can point to each item like this: items[i]['name'] or items[j]['value'] and so on...
2- Not preferred way: two different lists like this:
itemNames[items1,item2,item3, item4];
itemValues [90,180,270,360];
Then you can pass the itemNames list to your dropdownMenu and whenever an item has been selected you can find it's index and point to the itemsValues' appropriate row. For instance: dropdownMenu item3 selected so the returned index should be 2 (indexes are starting from 0) so you can find the desired value like this: desiredValue = itemsValue[2]; (270)
