![](/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.