I am trying to build a List of widgets dynamically
List<Widget> buildGrid(){
List<Widget> grid = new List<Widget>(3);
List<Widget> tiles = [];
int counter = 0;
for (int i = 0; i < 3; i++){
tiles = [];
for (int j = 0; j < 4; j++){
tiles.add(new GestureDetector(
onTap: (){
setState((){
toggleColor(counter);
});
},
child: new Container(
color: colors[counter],
width: 80.0,
height: 80.0,
margin: new EdgeInsets.all(11.3),
)
));
counter++;
}
grid[i] = new Row(
children: tiles,
);
counter = 0;
}
return grid;
}
The problem with this is, that the toggleColor of the newly added element is always 12. I meant it to add a new GestureDetector with the current iteration of counter, so that if the user clicks on an element, it only colors it. If I set counter to 3 for example, everything gets selected because it is still refering to the counter variable, instead of to the current interation, if you know what I mean.
Any suggestions on how I can solve this problem efficently?