我制作了一个如下所示的customGirdView
,一切都如我所料,但是我想在点击一个项目时创建一个事件,我无法获取每个项目的索引
,它总是 toast index
的最后一个值:
customGirdView(List<SuggestionsProductModel> data) {
List<Widget> widgets = List<Widget>();
int index = 0;
while (index < data.length) {
widgets.add(Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
/*item 1*/
Expanded(
child: InkWell(
onTap: () {
Fluttertoast.showToast(
msg: 'Clicked to ' + index.toString(),
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 1,
backgroundColor: Colors.black87,
textColor: Colors.white,
fontSize: 16.0);
},
child:Center()),
),
),
/*item 2*/
Expanded(
child: InkWell(
onTap: () {
Fluttertoast.showToast(
msg: 'Clicked to ' + (index + 1).toString(),
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 1,
backgroundColor: Colors.black87,
textColor: Colors.white,
fontSize: 16.0);
},
child: Center(),
),
),
],
));
index += 2;
}
return Column(
children: widgets,
);
}
最佳答案
使用 ListView.builder
怎么样?请在此处查看文档:https://api.flutter.dev/flutter/widgets/ListView/ListView.builder.html
ListView.builder(
itemCount: 2,
itemBuilder: (context, snapshot){
Expanded(
child: InkWell(
onTap: () {
Fluttertoast.showToast(
msg: 'Clicked to ' + (index).toString(),
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
timeInSecForIos: 1,
backgroundColor: Colors.black87,
textColor: Colors.white,
fontSize: 16.0);
},
child: Center(),
),
),
},
)
您不需要将 msg
指定为 index、index + 1、index + 2 等...只需引用 index
即可列表。 (可选)删除 itemCount
以使其无限长。
您还可以添加
if(index > x){
return null;
}
在任何给定索引处停止列表。
希望我能帮上忙。
关于android - 如何从列,行获取索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56303577/