'Is it possible to pick out an item from a list of widget's based on the widget's value in dart / flutter?
I have a list of PopupMenuItem<T> as part of showMenu and I need to access the key for any given item when its clicked. When you click on an item, the showMenu will give you the selected value.
So I first gave each PopupMenuItem a key, which is part of a List:
[
PopupMenuItem<int>-[<'Small'>],
PopupMenuItem<int>-[<'Medium'>],
PopupMenuItem<int>-[<'Large'>]
]
OR put another way:
items: [
PopupMenuItem<int>(
key: ValueKey('Small'),
value: 10,
child: Text('10'),
),
PopupMenuItem<int>(
key: ValueKey('Medium'),
value: 20,
child: Text('20'),
),
PopupMenuItem<int>(
key: ValueKey('Large'),
value: 30,
child: Text('30'),
),
],
Now when you tap on an item, or select an item you get returned the value of that item, which is great, but I want to get access to the key, which is the Small, Medium and Large listed above.
So is there a way to dive into a given list and get the item based on its value. If I have the item or at least its position in the list I can then get the key by doing :
((items[1].key) as ValueKey<String>).value.toString();
/// 1 represents the position in the list.
///That is what I need to try to get, or just get the whole item somehow
Solution 1:[1]
I would suggest using UniqueKey() for the key. You can build a simple solution for your use case.
You can have a map to store the values with the respective strings.
Map<int,String> data ={10, 'Small', 20: 'Medium', 30: 'Large' }
Once you get the value from the tap, you pass the value to the map to get the respective string:
e.g. data[value]
simple and fast
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | croxx5f |
