ListView 不会刷新,而附加列表会刷新 (Flutter) [英] ListView does not refresh whereas attached list does (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 在视觉上被我初始化它的 2 个元素卡住了.
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屋!