创建函数列表时,如何跟踪创建索引



我的代码看起来像这样:

list.add(TextButton(
onPressed: () {
int temp = index;
print(temp);
},
child: Text(myText),
));

然而,当我把这个列表放在一个小部件中,并尝试点击任何一个TextButtons时,我会得到循环的最后一个索引。

当我点击其中一个TextButton时,我如何才能得到它的正确索引?

这是完整的功能,

List<TableRow> generateTables() {
List<TableRow> list = [];
int index = 0;
for (Map element in exerciseList) {
String exName = element["name"];
Icon? icon = correspIcon(element);
list.add(
TableRow(
children: [
TextButton(
onPressed: () {
int temp = index;
print(temp);
},
style: TextButton.styleFrom(
minimumSize: Size.zero,
padding: const EdgeInsets.all(4.0),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
alignment: Alignment.centerLeft,
),
child: Text(
exName,
style: TextStyle(
fontFamily: "ArialRounded",
fontSize: 20,
color: Colors.white.withAlpha(240)),
),
),
icon ?? const SizedBox()
],
),
);
index++;
}
return list;
}

我想要的是,如果我点击列表中的第n个TextButton,返回的索引是n-1。

非常感谢你能帮我

使用它来获取所选元素的索引值上面的代码不起作用,因为索引值总是包含最后一个元素

List<TableRow> generateTables() {
List<TableRow> list = [];
for (var i=0; i<exerciseList.length; i++) {
final Map element= exerciseList[i];
String exName = element["name"];
Icon? icon = correspIcon(element);
list.add(
TableRow(
children: [
TextButton(
onPressed: () {
int temp = i;
print(temp);
},
style: TextButton.styleFrom(
minimumSize: Size.zero,
padding: const EdgeInsets.all(4.0),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
alignment: Alignment.centerLeft,
),
child: Text(
exName,
style: TextStyle(
fontFamily: "ArialRounded",
fontSize: 20,
color: Colors.white.withAlpha(240)),
),
),
icon ?? const SizedBox()
],
),
);
}
return list;
}

最新更新