Flutter,试图检查商品是否已添加到用户的购物车中,但该功能仅在发生
Flutter, trying to check if item added to cart for user, but the function is only happening
我正在尝试通过检查产品 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;
}
}
您正在为购物车中的每件商品调用 setState
。因此,当您为项目 2 调用它时,您将覆盖为项目 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;
});
我正在尝试通过检查产品 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;
}
}
您正在为购物车中的每件商品调用 setState
。因此,当您为项目 2 调用它时,您将覆盖为项目 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;
});