I am new to flutter. and I am trying to make an xo game. I am still on the very first steps of the app. I am using gridview.count to make the layout of the game. The problem is the properties of the stateful widget(choice, onTap()) is not defined in the gridview tile. This is my code
return Scaffold(
appBar: AppBar(title: Text('Tic Tac Toe')),
body: GridView.count(
crossAxisCount: 3,
crossAxisSpacing: 2.0,
mainAxisSpacing: 2.0,
children: List<Widget>.generate(
9,
(int index) {return new GridTile(
child:GridCell(
choice: _choice,
onTap: ()=>onTap(context),
),
);
})))
and the class is:
class GridCellState extends State<TicTacToe> {
final String choice;
final VoidCallback onTap;
GridCellState({Key key, this.choice, this.onTap}) :
super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap:onTap,
child:Container(
child: Text(choice),
height:20.0,
color:Theme.of(context).primaryColor,
),
);
}
}
Thanks in advance.
That is because you are wiring up the constructor in a wrong way, you do not construct the object from the State
object, that is the job of the StatefulWidget
is to construct the State
object. You construct an instance of a StatefulWidget
called GridCell
so GridCell
needs to have the fields and the constructor moved to it.
In short ,you need to move the GridCellState
fields and constructor up to the StatefulWidget
itself like this:
class GridCell extends StatefulWidget {
final String choice;
final VoidCallback onTap;
GridCell({Key key, this.choice, this.onTap}) :
super(key: key);
@override
GridCellState createState() {
return new GridCellState();
}
}
and then use widget.fieldName
from inside the State
object to access any field in the StatefulWidget
object, see I use widget.onTap
and widget.choice
to get fields data from my StatefulWidget
above.
class GridCellState extends State<GridCell> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap:widget.onTap,
child:Container(
child: Text(widget.choice),
height:20.0,
color:Theme.of(context).primaryColor,
),
);
}
}
Alternatively, you can just convert your GridCell
to a SatelessWidget
instead, both approaches will solve your issue so it depends whether you need to keep the StatefulWidget
or not.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.