Flutter购物车商品数量与价格更新异常问题求助
Problem Analysis
Your issue stems from three critical mistakes in your logic:
- Overwriting unit price with total price: You're storing the total price in the
productpricefield instead of keeping it as the unit price. This breaks all future calculations because each update uses the previous total instead of the original unit price. - Local state not synced with Firestore: The
_quantitystate variable isn't initialized or updated from the Firestore snapshot, leading to mismatches between local state and the actual stored value (especially after navigating back). - Using stale snapshot data for calculations: After updating the quantity in Firestore, you immediately use the old snapshot data (which hasn't refreshed yet) to compute the new price, resulting in incorrect values.
Solution Code
Here's the corrected implementation:
Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( snapshot.data!.docs[index]["Productname"], style: TextStyle( fontWeight: FontWeight.bold, fontSize: 16, ), ), SizedBox(height: 8), Row( children: [ // Calculate total price dynamically using unit price + quantity Text( "${int.parse(snapshot.data!.docs[index]["productprice"].toString()) * snapshot.data!.docs[index]["quantity"]}", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 16, ), ), SizedBox(width: 16), IconButton( icon: Icon(Icons.remove), onPressed: () async { int currentQuantity = snapshot.data!.docs[index]["quantity"]; if (currentQuantity > 1) { int newQuantity = currentQuantity - 1; await FirebaseFirestore.instance .collection('Cart') .doc(snapshot.data!.docs[index].id) .update({'quantity': newQuantity}); } }, ), SizedBox(width: 8), // Display quantity directly from snapshot Text( "${snapshot.data!.docs[index]["quantity"]}", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 16, ), ), SizedBox(width: 8), IconButton( icon: Icon(Icons.add), onPressed: () async { int currentQuantity = snapshot.data!.docs[index]["quantity"]; int newQuantity = currentQuantity + 1; await FirebaseFirestore.instance .collection('Cart') .doc(snapshot.data!.docs[index].id) .update({'quantity': newQuantity}); }, ), ], ), ], ),
Key Fixes Explained
- Preserve
productpriceas unit price: Never modify this field. The total price is always calculated dynamically asunit_price * quantityin the UI, ensuring all calculations use the original unit value. - Eliminate local
_quantitydependency: Read the current quantity directly from the Firestore snapshot when performing updates, removing state synchronization issues. - Leverage StreamBuilder auto-refresh: Any Firestore updates will trigger an automatic rebuild with the latest data, so manual
setStatecalls are unnecessary. - Single update operation: Each button press only modifies the
quantityfield in Firestore—no need to update price fields at all, since totals are computed on the fly.
Critical Pre-Requisite
Ensure your Firestore documents have correct initial data:
productprice: Must be the unit price of the item (e.g., 100 for your example, not 200)quantity: The number of items in the cart (e.g., 2 initially)
If you've already stored total prices in productprice, reset those fields to original unit prices first to fix existing data.
内容的提问来源于stack exchange,提问作者Muhammad Zohaib
相关产品推荐
相关产品推荐

