I see a lot of people with very similar problems, but nothing I try works.
CONTEXT
I have a list of favorited ideas. Whenever I click in a button inside the ideaItem, it should get removed from the list.
PROBLEM
When I delete any ideaItem, the last one from the screen gets always removed, instead of the one I clicked on. My FavoriteIdeasListView seems to update correctly the items count, this means that the attached List works, but the UI is not redrawing the ideaItems.
WHAT I HAVE TRIED
At the beginning I had the delete functionality directly on ideaItem, I read I should do a VoidCallback and handle deletion from the List itself, so it would notice the change. It didn't work
I also tried with a Stream Builder, so the stream would notify the ListView to refresh. Also it didn't work
I try calling SetState all the time and it's not reloading, it only builds the list at the beginning on the initialState.
class FavoritesList extends StatefulWidget {
FavoritesList({Key key}) : super(key: key);
@override
_FavoritesListState createState() => _FavoritesListState();
}
class _FavoritesListState extends State<FavoritesList> {
List<Idea> _favorites = [];
@override
void initState() {
super.initState();
favoritesInitialState();
}
Future <void> favoritesInitialState() async {
List<Idea> ideas = await IdeasDB.db.ideas();
setState(() {
_favorites = ideas;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Favorites')),
body: Center(
child: ListView.builder(
itemCount: _favorites.length,
itemBuilder: (context, index) {
final idea = _favorites[index];
return IdeaItem(
idea: idea,
onFavoriteToggle: () => deleteFromFavorites(idea),
);
},
),
)
);
}
void deleteFromFavorites(Idea idea) async {
await IdeasDB.db.deleteIdea(idea.url);
List<Idea> newIdeas = await IdeasDB.db.ideas();
setState(() {
this._favorites = newIdeas;
});
}
}