我有一个简单的网格,它比屏幕实际状态占用更多的空间,并且可以上下滚动。
每个单元格都有一个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()),
);
}),
);
}
}
Run Code Online (Sandbox Code Playgroud)
细胞小部件
...
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),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用 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),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
这是文档的链接: AutomaticKeepAliveClientMixin
在 Flutter Document 中ListView.builder提到,ListView当你滚动时,孩子们会根据需要构建......我认为这里也发生了同样的情况GridView.count
| 归档时间: |
|
| 查看次数: |
1775 次 |
| 最近记录: |