Flutter ListView doesn't refresh UI with setState(), although itemCount and attached list update correctly
I can see only two possible options for why this happens.
First one is obvious, your IdeasDB.db.deleteIdea(idea.url);
doesn't delete correct idea from DB;
The second one is less obvious, it's because your Element Tree couldn't recognize what's a widget you are trying to delete. It happens only with Stateful Widgets as your IdeaItem
could be.
Solution then is to use key
attribute for your IdeaItem
widgetlike this:
ListView.builder( itemCount: _favorites.length, itemBuilder: (context, index) { final idea = _favorites[index]; return IdeaItem( key: ValueKey(idea.url) // or UniqueKey() idea: idea, onFavoriteToggle: () => deleteFromFavorites(idea), ); },),
and in your IdeaItem
widget you have to pass that key to your parent Stateful widget
like in this example:
class IdeaItem extends StatefulWidget { final Idea idea; Function onFavoriteToggle; IdeaItem({Key key, this.idea, this.onFavoriteToggle}) : super(key: key); @override _IdeaItemState createState() => _IdeaItemState();}
Try to change
onFavoriteToggle: () => deleteFromFavorites(index),
and then
void deleteFromFavorites( int index) async { await IdeasDB.db.deleteIdea(idea.url); setState(() { this._favorites.removeAt(index); }); }
See if it works. If yes, there is probably error on deleteIdea()
.
Also, you know which item should be deleted, so you don't need to await to reload the List from your db. await IdeasDB.db.ideas();
If you want to be sure you can wrap your code with Try catch
void deleteFromFavorites(int index) async { try { await IdeasDB.db.deleteIdea(idea.url); setState(() { this._favorites.removeAt(index); }); } catch (_) { print('ERROR'); } }