作者:亿达口香糖 | 来源:互联网 | 2022-12-06 16:56
1> boformer..:
的确,它会无限循环,因为无论何时build
调用,都会调用它,updateList
并返回全新的未来。
你必须保持build
纯洁。它应该只读取并组合变量和属性,但绝不会引起任何副作用!
另一个注意事项:StatefulWidget
子类的所有字段都必须为final(widget.items = ...
不好)。更改的状态必须存储在State
对象中。
在这种情况下,您可以在将来自己存储结果(列表数据),而无需单独的字段。setState
从将来调用它甚至很危险,因为将来可能会在处置状态之后完成,并且会引发错误。
这是一些考虑了所有这些因素的更新代码:
class FeedListState extends State {
// no idea how you named your data class...
Future> _listFuture;
@override
void initState() {
super.initState();
// initial load
_listFuture = updateAndGetList();
}
void refreshList() {
// reload
setState(() {
_listFuture = updateAndGetList();
});
}
Future> updateAndGetList() async {
await widget.feeds.update();
// return the list here
return widget.feeds.getList();
}
@override
Widget build(BuildContext context) {
return new FutureBuilder>(
future: _listFuture,
builder: (BuildContext context, AsyncSnapshot> snapshot) {
if (snapshot.cOnnectionState== ConnectionState.waiting) {
return new Center(
child: new CircularProgressIndicator(),
);
} else if (snapshot.hasError) {
return new Text('Error: ${snapshot.error}');
} else {
final items = snapshot.data ?? []; // handle the case that data is null
return new Scrollbar(
child: new RefreshIndicator(
child: ListView.builder(
physics: const AlwaysScrollableScrollPhysics(), //Even if zero elements to update scroll
itemCount: items.length,
itemBuilder: (context, index) {
return FeedListItem(items[index]);
},
),
onRefresh: refreshList,
),
);
}
},
);
}
}