我在字母列表上编写了一个迭代,并使用“ map ”类将卡片放在屏幕上。
在代码中你可以看到我做了一行,并使用“ map ”将卡片上的所有用户板打印到屏幕上。我想在里面添加一些逻辑,所以我需要获取元素的 id(用于录制事件)。 有没有办法让我做到这一点?
实际上,我想在 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(),
)
],
),
}
Picture - each card is "element" of the map. I want to get the indexes for the function onTap.
最佳答案
要访问索引,您需要使用 asMap 将列表转换为 map 。运算符。
示例
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();
其他答案的引用
https://stackoverflow.com/questions/54990716/