![](/img/trans.png)
[英]How can I give a Variable from one class to another and return the changed variable back?
[英]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.