是否可以根据小部件在 dart / flutter 中的值从小部件列表中挑选一个项目?
Is it possible to pick out an item from a list of widget's based on the widget's value in dart / flutter?
我有一个 PopupMenuItem<T>
的列表作为 showMenu
的一部分,我需要在单击任何给定项目时访问 key
。当您单击一个项目时,showMenu
会给您 selected value
。
所以我首先给每个 PopupMenuItem
一个密钥,它是 List
:
的一部分
[
PopupMenuItem<int>-[<'Small'>],
PopupMenuItem<int>-[<'Medium'>],
PopupMenuItem<int>-[<'Large'>]
]
或者换句话说:
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'),
),
],
现在,当您点击一个项目或 select 一个项目时,您会返回该项目的 value
,这很棒,但我想访问 key
,也就是上面列出的Small
、Medium
和Large
。
那么有没有一种方法可以深入到给定列表并根据其 value
获取项目。如果我在列表中有 item
或至少它的 position
我可以通过以下方式获得 key
:
((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
我建议使用 UniqueKey() 作为密钥。您可以为您的用例构建一个简单的解决方案。
您可以有一个映射来存储具有相应字符串的值。
Map<int,String> data ={10, 'Small', 20: 'Medium', 30: 'Large' }
从点击中获取值后,将值传递给地图以获取相应的字符串:
例如数据[值]
简单快捷
我有一个 PopupMenuItem<T>
的列表作为 showMenu
的一部分,我需要在单击任何给定项目时访问 key
。当您单击一个项目时,showMenu
会给您 selected value
。
所以我首先给每个 PopupMenuItem
一个密钥,它是 List
:
[
PopupMenuItem<int>-[<'Small'>],
PopupMenuItem<int>-[<'Medium'>],
PopupMenuItem<int>-[<'Large'>]
]
或者换句话说:
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'),
),
],
现在,当您点击一个项目或 select 一个项目时,您会返回该项目的 value
,这很棒,但我想访问 key
,也就是上面列出的Small
、Medium
和Large
。
那么有没有一种方法可以深入到给定列表并根据其 value
获取项目。如果我在列表中有 item
或至少它的 position
我可以通过以下方式获得 key
:
((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
我建议使用 UniqueKey() 作为密钥。您可以为您的用例构建一个简单的解决方案。
您可以有一个映射来存储具有相应字符串的值。
Map<int,String> data ={10, 'Small', 20: 'Medium', 30: 'Large' }
从点击中获取值后,将值传递给地图以获取相应的字符串:
例如数据[值]
简单快捷