簡體   English   中英

如何避免將一個變量結果更改為另一個變量結果

[英]How can i avoid changing one variable result into a change of another

我有一個變量cart ,它是CartItem類型的購物車項目列表。 然后另一個變量selectedItem也是CartItem類型。 當我遍歷購物車並通過比較其 ID 是否等於所選項目的 ID 來獲取感興趣的項目時,我會更改其數量。 這工作正常並且符合預期。 挑戰是它導致 selectedItem 的數量也發生了變化。 單獨更改 selectedItem 的數量也會更改購物車項目的數量。 如果我同時更改兩者,則會發生雙增量。 為什么會發生這種情況,我該如何防止這種情況發生。 目的是改變兩者。 顯然,只改變一個我就能得到我想要的,但我需要了解發生了什么;

var cart = List<CartItem>();

var selectedItem = CartItem();

第一種情況

 for (CartItem item in cart) {
        if (item.product.id == selectedItem.product.id) {
          //this affects both selected item and item in cart's quantity
          item.quantity++;
          notifyListeners();
          printCart();
        }
      }

第二種情況

 for (CartItem item in cart) {
            if (item.product.id == selectedItem.product.id) {
              //this affects both selected item and item in cart's quantity
              selectedItem.quantity++;
              notifyListeners();
              printCart();
            }
          }

第三種情況

 for (CartItem item in cart) {
            if (item.product.id == selectedItem.product.id) {
              //this affects both selected item and item in cart's quantity
              //results in a double increment
              selectedItem.quantity++;
              item.quantity++;
              notifyListeners();
              printCart();
            }
          }

您正在創建的新實例CartItem()為您selectedCartItem ,而不是指你的一個List<CartItem> 您需要執行以下操作:

var cart = List<CartItem>();

var selectedItem = cart[index]; // where index is the position of the selected item

如果您不知道是哪個,您還可以執行以下操作:

var cart = List<CartItem>();

var selectedItem = cart.singleWhere((item) => item.product.id == selectedId);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM