![](/img/trans.png)
[英]How to make the inner stateful widget received the scroll event in Flutter?
[英]How to deal with a stateful widget as a child for grid.tile
我是新来的扑扑。 我正在尝试制作xo游戏。 我仍处于应用程序的第一步。 我正在使用gridview.count来制作游戏的布局。 问题是有状态窗口小部件(choice,onTap())的属性未在gridview磁贴中定义。 这是我的代码
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),
),
);
})))
该类是:
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,
),
);
}
}
提前致谢。
那是因为您以错误的方式连接了构造函数,而不是从State
对象构造对象,所以StatefulWidget
的工作就是构造State
对象。 您构造了一个名为GridCell
的StatefulWidget
实例,因此GridCell
需要将字段和构造函数移至该实例。
简而言之,您需要像这样将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();
}
}
然后使用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,
),
);
}
}
或者,您可以只将GridCell
转换为SatelessWidget
,这两种方法都可以解决您的问题,因此这取决于您是否需要保留StatefulWidget
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.