You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 productprice field 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 _quantity state 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 productprice as unit price: Never modify this field. The total price is always calculated dynamically as unit_price * quantity in the UI, ensuring all calculations use the original unit value.
  • Eliminate local _quantity dependency: 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 setState calls are unnecessary.
  • Single update operation: Each button press only modifies the quantity field 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:45:19