[英]How to deal with a stateful widget as a child for grid.tile
I am new to flutter. 我是新来的扑扑。 and I am trying to make an xo game.
我正在尝试制作xo游戏。 I am still on the very first steps of the app.
我仍处于应用程序的第一步。 I am using gridview.count to make the layout of the game.
我正在使用gridview.count来制作游戏的布局。 The problem is the properties of the stateful widget(choice, onTap()) is not defined in the gridview tile.
问题是有状态窗口小部件(choice,onTap())的属性未在gridview磁贴中定义。 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. 那是因为您以错误的方式连接了构造函数,而不是从
State
对象构造对象,所以StatefulWidget
的工作就是构造State
对象。 You construct an instance of a StatefulWidget
called GridCell
so GridCell
needs to have the fields and the constructor moved to it. 您构造了一个名为
GridCell
的StatefulWidget
实例,因此GridCell
需要将字段和构造函数移至该实例。
In short ,you need to move the GridCellState
fields and constructor up to the StatefulWidget
itself like this: 简而言之,您需要像这样将
GridCellState
字段和构造函数移至StatefulWidget
本身:
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. 然后使用
State
对象中的widget.fieldName
访问StatefulWidget
对象中的任何字段,请参阅上面的我使用widget.onTap
和widget.choice
从我的StatefulWidget
获取字段数据。
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. 或者,您可以只将
GridCell
转换为SatelessWidget
,这两种方法都可以解决您的问题,因此这取决于您是否需要保留StatefulWidget
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.