state - 如何在 Flutter 中滚动时保持状态?
问题描述
我有一个简单的网格,它比屏幕真实状态占用更多空间,并且可以上下滚动。
每个单元格都有一个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()),
);
}),
);
}
}
细胞小部件
...
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),
),
);
}
}
解决方案
您可以使用 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
推荐阅读
- java - 垃圾收集加载画面
- javascript - 如何在数据表中自动修复下一页
- javascript - 反应 - 发布错误响应后不刷新页面
- ruby - 如何从ruby的shell脚本调用函数
- c# - 无法在 .NET Razor 页面中创建会话
- vba - 用另一个表字段丰富一个字段的信息
- python-asyncio - 管理异步任务
- docker-compose - 如何为 pdftotext 正确安装 poppler
- reactjs - React.cloneElement 如何与 chldren 一起使用?
- apache-kafka - kafka-avro-console-consumer:为 schema-registry 指定信任库位置