从 List.map() 获取迭代索引 [英] Get iteration index from List.map()
问题描述
我在字母列表上写了一个迭代,并使用地图"将卡片放在屏幕上班级.
I wrote an iteration on list of letters and put inside cards on screen using "map" class.
在代码中你可以看到我做了一行,并使用了map"将卡片上的所有用户板打印到屏幕上.我想在里面添加一些逻辑,所以我需要获取元素的 id(用于录音事件).有没有办法做到这一点?
In the code you can see that I made a row, and using "map" printed all the userBoard on cards to the screen. I want to add some logic inside so I need to get the id of the element (for taping event). Is there a way that I can do that?
实际上,我想通过 userBoard 获取元素的特定索引.
Actually, I want to get a specific index of element over userBoard.
代码:
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Row(
children: userBoard
.map((element) => Stack(children: <Widget>[
Align(
alignment: Alignment(0, -0.6),
child: GestureDetector(
onTap: (() {
setState(() {
// print("element=${element.toString()}");
// print("element=${userBoard[element]}");
});
}),
child: SizedBox(
width: 40,
height: 60,
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0),
),
child: Center(
child: Text(element,
style: TextStyle(fontSize: 30)),
)),
),
),
)
]))
.toList(),
)
],
),
}
图片 - 每张卡片都是元素";地图的.我想获取 onTap 函数的索引.
Picture - each card is "element" of the map. I want to get the indexes for the function onTap.
推荐答案
要访问索引,您需要使用 asMap 运算符.
To get access to index, you need to convert your list to a map using the asMap operator.
示例
final fruitList = ['apple', 'orange', 'mango'];
final fruitMap = fruitList.asMap(); // {0: 'apple', 1: 'orange', 2: 'mango'}
// To access 'orange' use the index 1.
final myFruit = fruitMap[1] // 'orange'
// To convert back to list
final fruitListAgain = fruitMap.values.toList();
您的代码
userBoard.asMap().map((i, element) => MapEntry(i, Stack(
GestureDetector(onTap: () {
setState(() {
// print("element=${element.toString()}");
// print("element=${userBoard[i].toString()}");
});
}),
))).values.toList();
这篇关于从 List.map() 获取迭代索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!