I’m facing an issue with updating the UI in my Flutter app after removing an item from a list. I’m using a FutureBuilder
to fetch data asynchronously, and I want to allow users to remove items from a list of favorites. However, when I call setState
to remove an item from the list and update the UI, it doesn’t reflect the changes.
List<Favorite> favorites = [];
// Use FutureBuilder to fetch the list of favorites.
FutureBuilder(
future: placeBloc.getFavorites(),
builder: (BuildContext context, AsyncSnapshot<List<Favorite>> favListSnapshot) {
if(favListSnapshot.hasData){
// Store the list of favorites in the variable.
favorites = favListSnapshot.data!;
return Expanded(
child: ListView.builder(
itemCount: favorites.length,
itemBuilder: (context, index){
return GestureDetector(
onTap: () {
// Remove favorite from the list.
setState(() {
favorites.removeAt(index);
});
// Remove favorite from the database...
},
child: Card(
// Card details...
child: Container(
// Container details...
child: Row(
children: [
// Widget details...
GestureDetector(
onTap: () {
// Remove favorite from the list.
setState(() {
favorites.removeAt(index);
});
},
child: SizedBox(
width:30,
child: Image.asset("assets/images/heartBlack.png",width:25,height:25),
),
)
],
),
)
),
);
}
)
);
} else {
// Handle loading state...
}
}
)
I’ve tried calling setState to remove an item from the list of favorites within the GestureDetector's
onTap callback. I expected this to trigger a rebuild of the UI, reflecting the updated list without the removed item. However, even though setState
is being called and the item is removed from the list, the UI does not update as expected.
I’ve also verified that the FutureBuilder
correctly fetches the list of favorites, and there are no errors or exceptions thrown in the process.
Any suggestions on how to fix this issue would be greatly appreciated!