我试图通过检查产品ID和用户ID是否在相同的购物车项目中可用来检查产品是否添加到购物车中,但此功能仅适用于插入的最后一个购物车项目。
数据库:

右边的商品是最后添加到购物车中的,中间和左边的商品是首先添加的:

我希望我的想法是清楚的
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;
}
}发布于 2021-11-09 14:51:36
您将为购物车中的每个商品调用setState。因此,当您为item 2调用它时,您将覆盖为item 1设置的状态。
相反,您应该只使用循环来检查是否可以在购物车中找到任何匹配的商品,然后在循环完成后调用setState:
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;
});https://stackoverflow.com/questions/69898322
复制相似问题