Home > Software engineering >  Flutter, trying to check if item added to cart for user, but the function is only happening
Flutter, trying to check if item added to cart for user, but the function is only happening

Time:11-10

i am trying to Check of product is added to cart or not by checking if product ID and user ID are available in the same cart item, but this function doesn't work only for last cart item inserted.

Database: Databse

item on the right was last added to cart, the one in the middle and on the left were firstly added:

i hope my idea is clear

checkItemAddedToCart() async {
  try {
    var collectionRef = await databseRefrence.child("Cart").get();
    Map<dynamic, dynamic> values = collectionRef.value;
    values.forEach((key, values) {
      if (values['productId'] == widget.pid && values['userId'] == Id) {
        //this is only happening on the last item added to cart!
        setState(() {
          buttonText = "Added to cart!!";
          addCartButton = true;
        });
      } else {
        setState(() {
          buttonText = "Add to cart";
          addCartButton = false;
        });
      }
    });
  } catch (e) {
    throw e;
  }
}

CodePudding user response:

You're calling setState for each item in the cart. So when you call it for item 2, you're overwriting the state that you had set for item 1.

Instead you should only use the loop to check if you can find any matching item in the cart, and then call setState after the loop completes:

var found = false;
values.forEach((key, values) {
  if (values['productId'] == widget.pid && values['userId'] == Id) {
    found = true
  }
}
setState(() {
  buttonText = found ? "Added to cart!!" : "Add to cart";
  addCartButton = found;
});
  • Related