我是扑扑的新手,我正在尝试打井字游戏;尽管遵循Flutter GestureDetector, onTap gets triggered automatically, how to?
中的相同概念,但我还是有一些建议我的代码最初以红色和空白文本返回网格单元格
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(' '),
);
})));
然后,网格单元格的类为:
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,
),
);
}
}
预期的行为是出现9个redgridcells,当我按其一个将其文本变成X并且其颜色变为浅蓝色时,第二次在另一个单元格上按将具有文本O,颜色为浅蓝色,而第三次则为X,因此上。实际行为是9个蓝色网格单元,当我按它们中的任何一个时,都不会改变!
提前感谢:)
答案 0 :(得分:0)
由于choice
初始化为null并且在与Text(choice)
或条件语句一起使用之前从未真正具有值,因此您会收到错误消息。
答案 1 :(得分:0)
向GestureDetector的Container子项添加颜色:Colors.transparent 。
您的小部件将显示为:
@override
Widget build(BuildContext context) {
return new GestureDetector(
onTap:()=>_changeCell(widget.index),
child:Container(
height:20.0,
color:Theme.of(context).primaryColor,
),
);
}