Reputation: 359
I have a Listview.builder()
inside a FutureBuilder()
that displays data fetched from API. I can retrieve the data successfully. But when I call the refreshData()
function, previous data gets appended in the list.. How do I properly 'refresh' the widgets inside a FutureBuilder()
?
Note: I'm only using get
request here, so it's impossible that the data gets duplicated in the back-end. So the problem actually lies in displaying the data.
Here is my code:
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!'));
}
},
)
],
),
),
);
}
}
Upvotes: 0
Views: 318
Reputation: 359
As @pskink mentioned in the comment above, I just replaced _givers.addAll(await NetworkHelper().fetchGivers());
with _givers = await NetworkHelper().fetchGivers();
Thanks for the help!
Upvotes: 1