How to keep state, on scroll in Flutter?

[亡魂溺海] 提交于 2021-02-07 17:24:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!