[英]How can i avoid changing one variable result into a change of another
I have a variable cart
which is a list of cart items of type CartItem
.我有一个变量cart
,它是CartItem
类型的购物车项目列表。 Then a another variable selectedItem
also of type CartItem
.然后另一个变量selectedItem
也是CartItem
类型。 When i loop through cart and get the item of interest by comparing if its ID is equal to the ID of the selected item, I change its quantity.当我遍历购物车并通过比较其 ID 是否等于所选项目的 ID 来获取感兴趣的项目时,我会更改其数量。 That works fine and expected.这工作正常并且符合预期。 Challenge is it results into the selectedItem's quantity also changing.挑战是它导致 selectedItem 的数量也发生了变化。 Also changing the selectedItem's quantity alone changes the quantity of the cart item.单独更改 selectedItem 的数量也会更改购物车项目的数量。 If I change both then a double increment occurs.如果我同时更改两者,则会发生双增量。 Why is that happening and how can i prevent that.为什么会发生这种情况,我该如何防止这种情况发生。 The aim is to change both.目的是改变两者。 Obviously by changing only one I can get what I want but I need to understand what is going on;显然,只改变一个我就能得到我想要的,但我需要了解发生了什么;
var cart = List<CartItem>();
var selectedItem = CartItem();
First case第一种情况
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();
}
}
Second case第二种情况
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();
}
}
Third case第三种情况
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();
}
}
You are creating a new instance of CartItem()
for your selectedCartItem
instead of referring to one of your List<CartItem>
.您正在创建的新实例CartItem()
为您selectedCartItem
,而不是指你的一个List<CartItem>
You need to do something like:您需要执行以下操作:
var cart = List<CartItem>();
var selectedItem = cart[index]; // where index is the position of the selected item
If you don't know which one is, you can also do something like:如果您不知道是哪个,您还可以执行以下操作:
var cart = List<CartItem>();
var selectedItem = cart.singleWhere((item) => item.product.id == selectedId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.