I'm basically creating a game where a grid is getting generated dynamically. It creates the tiles, adds them to a list and uses that list as an argument for the children parameter. What I find difficult however is combining it with fixed widgets.
Let's say on top of everything, I want a text element. The problem I now encounter is that if I assign my dynamically generated content like this:
...
children: mycontent,
...
then I have nowhere to put my hard coded widgets. I hope you know what I mean. Until now, I have solved it by creating a larget list and copying the dynamically generated elements over, and afterwards adding my hard-coded widgets:
Widget buildTile(int counter) {
return new GestureDetector(
onTap: (){
setState((){
toggleColor(counter);
});
},
child: new Container(
color: colors[counter],
foregroundDecoration: new BoxDecoration(
border: new Border(),
),
width: 75.0,
height: 75.0,
margin: new EdgeInsets.all(2.0),
)
);
}
List<Widget> buildGrid(){
Map dimensions = {"width" : 4, "height" : 6};
List<Widget> grid = new List<Widget>(dimensions["height"]);
List<Widget> tiles = [];
int counter = 0;
for (int i = 0; i < dimensions["height"]; i++){
tiles = [];
for (int j = 0; j < dimensions["width"]; j++){
tiles.add(buildTile(counter));
counter++;
}
grid[i] = new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: tiles,
);
}
return grid;
}
List<Widget> copyElements(List<Widget> from){
List<Widget> to = [];
for (int i = 0; i < from.length; i++){
to.add(from[i]);
}
return to;
}
List<Widget> buildPlayground(List<Widget> grid){
List<Widget> playground = [];
playground = copyElements(grid);
playground.add(new Padding(
padding: new EdgeInsets.all(20.0),
child: new RaisedButton(
color: Colors.purple,
child: new Container(
width: 100.0,
child: new Center(
child: new Text("Done", style: new TextStyle(fontSize: 20.0)),
),
),
onPressed: (){
}
),
));
return playground;
}
@override
build(BuildContext context){
return new Scaffold(
appBar: new AppBar(
title: new Text("Game"),
),
body: new Container(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: buildPlayground(buildGrid()),
)
),
);
}
It kinda works, but is very tedious as soon as I figure out that I want to add another hard coded widget. Any suggestions for how I can address this problem? Thanks
I guess this is the way to go, however you could use the GridView widget, and you could create a TileWidget
instead of you buildTile
function. Using GridView
should clean your code, but what do you mean by hard-coded widgets ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With