Want to use FutureBuilder with setState in flutter? It’s even dangerous to call setState from a future, because the future might complete after the disposal of the state, and it will throw an error.
Here is some update code that takes into account all of these things:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | class FeedListState extends State<FeedList> { // no idea how you named your data class... Future<List<ItemData>> _listFuture; @override void initState() { super.initState(); // initial load _listFuture = updateAndGetList(); } void refreshList() { // reload setState(() { _listFuture = updateAndGetList(); }); } Future<List<ItemData>> updateAndGetList() async { await widget.feeds.update(); // return the list here return widget.feeds.getList(); } @override Widget build(BuildContext context) { return new FutureBuilder<List<ItemData>>( future: _listFuture, builder: (BuildContext context, AsyncSnapshot<List<ItemData>> 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 ?? <ItemData>[]; // 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, ), ); } }, ); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.