I am new to flutter and I'm trying to make tic tac toe game; i had some on ontap despite following the same concept in Flutter GestureDetector, onTap gets triggered automatically, how to?
My code to return the gridcells intially with red color and blank text
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 GridCell(
index:index,
color: Colors.red,
text:Text(' '),
);
})));
Then the class of the gridcell is:
class GridCell extends StatefulWidget {
final Color color;
final Text text;
final int index;
GridCell({Key key, this.color,this.text,this.index}) :
super(key: key);
@override
GridCellState createState() {
return new GridCellState();
}
}
class GridCellState extends State<GridCell> {
Color cellColor=Colors.white;
Text cellText=new Text(' ');
String choice=' ';
@override
void initState() {
super.initState();
choice;
cellColor=widget.color;
cellText=widget.text;
}
//get text function to switch the x and o between the players
String _getText(){
if (choice=='X'){
choice='O';
}
else{
choice='X';
}
return choice;
}
_changeCell(index) {
setState(() {
switch (index) {
case 0:
cellColor = Colors.lightBlue;
cellText = new Text(choice);
print(_getText());
break;
case 1:
cellColor = Colors.lightBlue;
cellText = new Text(_getText());
print(_getText());
print(_getText());
break;
case 2:
cellColor = Colors.lightBlue;
cellText = new Text(_getText());
print(_getText());
break;
case 3:
cellColor = Colors.lightBlue;
cellText = new Text(_getText());
print(_getText());
break;
case 4:
cellColor = Colors.lightBlue;
cellText = new Text(_getText());
print(_getText());
break;
case 5:
cellColor = Colors.lightBlue;
cellText = new Text(_getText());
print(_getText());
break;
case 6:
cellColor = Colors.lightBlue;
cellText = new Text(_getText());
print(_getText());
break;
case 7:
cellColor = Colors.lightBlue;
cellText = new Text(_getText());
print(_getText());
break;
case 8:
cellColor = Colors.lightBlue;
cellText = new Text(_getText());
print(_getText());
break;
}
});
}
@override
Widget build(BuildContext context) {
return new GestureDetector(
onTap:()=>_changeCell(widget.index),
child:Container(
height:20.0,
color:Theme.of(context).primaryColor,
),
);
}
}
The expected behaviour is 9 redgridcells appears and when i press one of the its text turns into X and its color turns into lightblue, the second press on another cell will have text O and color light blue the third's text is X and so on. The actual behaviour is 9 blue gridcells and when i press any of them nothing changes!
Thanks in advance:)