我有一个简单的网格,比屏幕的实际状态占用更多的空间,并且可以上下滚动。
每个单元格都有onTap()
方法,可以更改单元格颜色。
问题是,一旦我将更改的单元格滚出视图,就不会保留状态。
有什么想法吗?
class GridWidget extends StatefulWidget {
@override
_GridWidgetState createState() => new _GridWidgetState();
}
class _GridWidgetState extends State<GridWidget> {
@override
Widget build(BuildContext context) {
Color cellColor = Colors.white;
return new GridView.count(
crossAxisCount: 10,
children: new List.generate(100, (index) {
return new CellWidget(
index: index,
color: cellColor,
text: new Text(index.toString()),
);
}),
);
}
}
CellWidget
...
class _CellWidgetState extends State<CellWidget> {
Color cellColor = Colors.white;
Text cellText = new Text('white');
@override
void initState() {
super.initState();
cellColor = widget.color;
cellText = widget.text;
}
_changeCell(index) {
setState(() {
cellColor = Colors.lightBlue;
});
}
@override
Widget build(BuildContext context) {
return new GestureDetector(
onTap: () => _changeCell(widget.index),
child: new Container(
width: double.infinity,
height: double.infinity,
child: new Center(child: cellText),
),
);
}
}
答案 0 :(得分:0)
ListView.builder
的Flutter文档中,提到ListView
个孩子会在滚动时按需建立...我认为GridView.count
答案 1 :(得分:0)
您可以使用AutomaticKeepAliveClientMixin类来防止滚动时丢弃您的项目。 在CellWidget中更改代码应该可以解决您的问题:
class _CellWidgetState extends State<CellWidget> with AutomaticKeepAliveClientMixin {
Color cellColor = Colors.white;
Text cellText = new Text('white');
@override
bool get wantKeepAlive => true;
@override
void initState() {
super.initState();
cellColor = widget.color;
cellText = widget.text;
}
_changeCell(index) {
setState(() {
cellColor = Colors.lightBlue;
});
}
@override
Widget build(BuildContext context) {
super.build(context);
return new GestureDetector(
onTap: () => _changeCell(widget.index),
child: new Container(
width: double.infinity,
height: double.infinity,
child: new Center(child: cellText),
),
);
}
}
以下是文档的链接: AutomaticKeepAliveClientMixin