How to change icon when the product item was added in to cart? I am using provider for writing some logic of adding items to cart. The function works fine, but I don't get it how to dynamically change icon if only one item was added. I don't want to change all icons when I pressed the button as it does setState method, because ot update all buttons states.
Now my code is like this:
class AddToCart with ChangeNotifier {
final Map<int, Item> _productCart = {};
Map<int, Item> get itemsInCart {
return _productCart;
}
void addInCart({ final int id}) {
if (_productCart.containsKey(id)) {
_productCart.update(id, (value) => Item(
id: value.id
));
print(_productCart);
} else {
_productCart.putIfAbsent(
id, () => Item(id: id));
print('object');
}
notifyListeners();
}
void removeFromCart(final int id){
//...Some logic
isAdd = false;
}
bool _isAdd = true;
bool get isAdd => _isAdd;
set isAdd(bool value) {
_isAdd = value;
notifyListeners();
}
}
and in my ui I am trying to update the state of Icon when user clicked to heart icon, But now it dosen't work:
Consumer<AddToCart>(builder: (ctx, value, child) {
return IconButton(
onPressed: () {
cart.addInCart();
context
.read<AddToCart>().removeFromCart(providerGridPagination.itemgrid[index]);
},
icon: FaIcon(
cart.isAdd ? FontAwesomeIcons.heart : FontAwesomeIcons.heartBroken, color: Colors.red,
));
I did as @Tim explained to me, but I got the all icons changed not only one which was added to favs. How can I fixed it?