我試圖通過檢查產品 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;
}
}
uj5u.com熱心網友回復:
您正在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;
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/354858.html
上一篇:Flutter使用SharedPreferences和Json來存盤物件
下一篇:滾動時小部件溢位容器
