我在Listview.builder()
中有一个FutureBuilder()
,其中显示了从API提取的数据。我可以成功检索数据。但是,当我调用refreshData()
函数时,以前的数据将添加到列表中。如何正确“刷新” FutureBuilder()
中的窗口小部件?
注意:我在这里仅使用get
请求,因此不可能在后端重复数据。因此,问题实际上出在显示数据上。
这是我的代码:
class _MyHomePageState extends State<MyHomePage> {
List<Giver> _givers = [];
Future giversList;
getData() async {
_givers.addAll(await NetworkHelper().fetchGivers());
return _givers;
}
refreshData() {
giversList = getData();
}
@override
void initState() {
super.initState();
giversList = getData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
RaisedButton(
onPressed: (){
setState(() {
refreshData();
});
},
child: Text('Refresh'),
),
FutureBuilder(
future: giversList,
builder: (context, snapShot){
switch(snapShot.connectionState) {
case ConnectionState.none:
return Center(child: Text('none'));
case ConnectionState.active:
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
//this is where the listview is created
case ConnectionState.done:
return ListView.builder(
shrinkWrap: true,
itemCount: _givers.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapShot.data[index].name),
subtitle: Text(snapShot.data[index].address),
);
});
default:
return Center(child: Text('Default!'));
}
},
)
],
),
),
);
}
}
答案 0 :(得分:1)
就像@pskink在上面的评论中提到的那样,我只是将_givers.addAll(await NetworkHelper().fetchGivers());
替换为_givers = await NetworkHelper().fetchGivers();
感谢您的帮助!