'How to get index from Column, Row
I made a customGirdView
like below, everything as I expected, but I want to make an event when I click an item, I cannot get the index
of each item, it always toasts the last value of 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,
);
}
Solution 1:[1]
How about using a ListView.builder
? See doc here: 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(),
),
),
},
)
You wouldn't need to specify your msg
as index, index + 1, index + 2, etc... just refer to index
and it goes through the list. Optionally, remove the itemCount
to make it infinitely long.
You can also add
if(index > x){
return null;
}
to stop the list at any given index.
Hope I could help.
Solution 2:[2]
Index can be added and can get for child widget as mentioned in the below article. The articale is written by my self. Assuming that the inforamtion is more relevant here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Marc Köhler |
Solution 2 |