【发布时间】:2019-01-31 22:09:13
【问题描述】:
如何正确使用FutureBuilder 和setState?例如,当我创建一个有状态小部件时,它开始加载数据(FutureBuilder),然后我应该用新数据更新列表,所以我使用 setState,但它开始无限循环(因为我再次重建小部件),任何解决方案?
class FeedListState extends State<FeedList> {
Future<Null> updateList() async {
await widget.feeds.update();
setState(() {
widget.items = widget.feeds.getList();
});
//widget.items = widget.feeds.getList();
}
@override
Widget build(BuildContext context) {
return new FutureBuilder<Null>(
future: updateList(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Center(
child: new CircularProgressIndicator(),
);
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return new Scrollbar(
child: new RefreshIndicator(
child: ListView.builder(
physics:
const AlwaysScrollableScrollPhysics(), //Even if zero elements to update scroll
itemCount: widget.items.length,
itemBuilder: (context, index) {
return FeedListItem(widget.items[index]);
},
),
onRefresh: updateList,
),
);
}
},
);
}
}
【问题讨论】:
-
使用
FutureBuilder的全部意义在于不自己调用setState。 -
我明白,但我想以某种方式在使用 FutureBuilder 首次启动后更新数据(来自互联网)