问题
I have a simple grid, that takes more space than the screen real-state, and can be scrolled up and down.
Each cell has an onTap()
method that changes the cell color.
The problem is that once I scroll the changed cell out of view, the state is not kept.
Any ideas?
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()),
);
}),
);
}
}
The 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),
),
);
}
}
回答1:
in Flutter Document for ListView.builder
has mentioned that ListView
children will build on demand when you scroll... i think here same situation is happening with GridView.count
回答2:
You can use AutomaticKeepAliveClientMixin class to prevent your items to be disposed when scrolled. Changing the code in CellWidget should resolve your problem:
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),
),
);
}
}
Here is the link to the documentation: AutomaticKeepAliveClientMixin
来源:https://stackoverflow.com/questions/50067901/how-to-keep-state-on-scroll-in-flutter