如何保持状态,在Flutter中滚动? [英] How to keep state, on scroll in Flutter?

查看:61
本文介绍了如何保持状态,在Flutter中滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple grid, that takes more space than the screen real-state, and can be scrolled up and down.

每个单元格都有一个更改单元格颜色的 onTap()方法.

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.

有什么想法吗?

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

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

Flutter文档中针对 ListView.builder

推荐答案

提到,当您滚动时, ListView 子级将按需构建...我认为 GridView.count

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

这篇关于如何保持状态,在Flutter中滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆