我做了一个customGirdView
,就像我期望的一样,但是当我单击一个项目时我想创建一个事件,我无法获得每个项目的index
,它总是为最后一个敬酒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,
);
}
答案 0 :(得分:0)
如何使用ListView.builder
?在此处查看文档:{{3}}
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
指定为索引,索引+ 1,索引+ 2等……只需参考index
,它就会遍历列表。 (可选)删除itemCount
以使其无限长。
您也可以添加
if(index > x){
return null;
}
在任何给定索引处停止列表。
希望我能帮上忙。