如何保持状态,在Flutter滚动?

时间:2018-04-27 18:00:14

标签: state flutter

我有一个简单的网格,比屏幕的实际状态占用更多的空间,并且可以上下滚动。

每个单元格都有onTap()方法,可以更改单元格颜色。

问题是,一旦我将更改的单元格滚出视图,就不会保留状态。

有什么想法吗?

enter image description here

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()),
        );
      }),
    );
  }
}

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),
      ),
    );
  }
}

2 个答案:

答案 0 :(得分:0)

ListView.builder的Flutter文档中,

提到ListView个孩子会在滚动时按需建立...我认为GridView.count

在这种情况下会发生同样的情况

答案 1 :(得分:0)

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