Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Build Widgets dynamically

Tags:

flutter

dart

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?

like image 511
OhMad Avatar asked May 19 '17 16:05

OhMad


People also ask

How do you display data dynamically in flutter?

How do you show dynamic data in Flutter? We can use ListView. builder(..) in Stateless Widgets if we want to display dynamic (different) contents every time the widget is loaded within an application. With Stateful widgets, it can change the contents of the screen dynamically.

Can we build custom widgets in flutter?

Using our custom widget editor, you can add any widget to your project. You can write/modify the widget code or upload it directly in the UI editor. It allows you to define parameters that can be used to customize the widget. You can compile and preview the custom widget right inside the code editor.


1 Answers

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

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

Then you can say:

onTap: _createTapHandler(counter)

Perhaps a more maintainable solution would be to create a method that builds your GestureRecognizer. Then you could configure 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 could refactor that build function into its own StatelessWidget if you want to be even more maintainable.

like image 185
Collin Jackson Avatar answered Oct 13 '22 08:10

Collin Jackson