首页 > 解决方案 > 如何在 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),
      ),
    );
  }
}

标签: stateflutter

解决方案


您可以使用 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


推荐阅读