ListView不会刷新,而附加列表会刷新(Flutter) [英] ListView does not refresh whereas attached list does (Flutter)

查看:503
本文介绍了ListView不会刷新,而附加列表会刷新(Flutter)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图熟悉颤动,并且遇到了一些奇怪的情况。我想建立一个动态的 ListView ,其中 + 按钮允许添加元素。我编写了以下状态代码:

I'm trying to get familiar with flutter and I'm facing some weird case. I want to build a dynamic ListView where a + button allows to add elements. I wrote the following State code:

class MyWidgetListState extends State<MyWidgetList> {
  List<Widget> _objectList = <Widget>[
    new Text('test'),
    new Text('test')
  ];

  void _addOne() {
    setState(() {
      _objectList.add(new Text('test'));
    });
  }

  void _removeOne() {
    setState(() {
      _objectList.removeLast();
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Column(
      children: <Widget>[
        new ListView(
          shrinkWrap: true,
          children: _objectList
        ),
        new Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new IconButton(
              icon: new Icon(Icons.remove_circle),
              iconSize: 36.0,
              tooltip: 'Remove',
              onPressed: _objectList.length > 2 ? _removeOne : null,
            ),
            new IconButton(
              icon: new Icon(Icons.add_circle),
              iconSize: 36.0,
              tooltip: 'Add',
              onPressed: _addOne,
            )
          ],
        ),
        new Text(_objectList.length.toString())
      ],
    );
  }
}

我的问题是ListView在视觉上与

My problem here is that the ListView is visually stuck with the 2 elements I initialized it with.

内部的 _objectList 管理得很好。为了进行测试,我在底部添加了一个简单的 Text 小部件,该小部件显示了列表的大小。当我单击添加/删除按钮并正确刷新时,此选项可以正常工作。我是否缺少某些东西?

Internally the _objectList is well managed. For testing purpose I added a simple Text widget at the bottom that shows the size of the list. This one works fine when I click the Add/Remove buttons and it gets properly refreshed. Am I missing something?

推荐答案

Flutter基于不可变数据。这意味着,如果对一个对象的引用没有更改,则内容也没有更改。

Flutter is based around immutable data. Meaning that if the reference to an object didn't change, the content didn't either.

问题是,在您的情况下,您始终发送给 ListView 相同的数组,而是改变其内容。但这会导致 ListView 假定列表未更改,因此可以防止无用的渲染。

The problem is, in your case you always send to ListView the same array, and instead mutate its content. But this leads to ListView assuming the list didn't change and therefore prevent useless render.

您可以更改 setState 来记住这一点:

You can change your setState to keep that in mind :

setState(() {
  _objectList = List.from(_objectList)
    ..add(Text("foo"));
});

这篇关于ListView不会刷新,而附加列表会刷新(Flutter)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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