title: Flutter - Build Widgets dynamically
body: <p>I am trying to build a List of widgets dynamically</p>
  
  <pre><code>List&lt;Widget&gt; buildGrid(){
  List&lt;Widget&gt; grid = new List&lt;Widget&gt;(3);
  List&lt;Widget&gt; tiles = [];
  int counter = 0;
  
  for (int i = 0; i &lt; 3; i++){
    tiles = [];
    for (int j = 0; j &lt; 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;
  
  
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>Any suggestions on how I can solve this problem efficently?</p>