Flutter - dynamically create widgets

I am trying to dynamically create a list of widgets

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 is that the toggleColor of the newly added element is always 12. I meant that it adds a new GestureDetector with the current counter iteration, so that if the user clicks on the element, it only colors it, For example, if I set the counter to 3, everything is selected because it still refers to the counter variable and not the current interaction if you know what I mean.

Any suggestions for an efficient solution to this problem?

+3


source to share


1 answer


You need to capture the current value of the counter variable in the closure:

final _createTapHandler = (value) {
    setState(() => toggleColor(value));
};

      

Then you can say:

onTap: _createTapHandler(counter)

      



Perhaps a more convenient solution would be to create a method that your GestureRecognizer creates. Then you can customize it with the counter value.

Widget buildTile(int tileCounter) {
  return new GestureDetector(
    onTap: (){
      setState((){
        toggleColor(tileCounter);
      });
    },
    child: new Container(
      color: colors[tileCounter],
      width: 80.0,
      height: 80.0,
      margin: new EdgeInsets.all(11.3),
    )
  );
}

      

You can refactor this build function into your own StatelessWidget if you want to be even more serviceable.

+3


source







All Articles