Flutter 如何避免将一个变量的结果更改为另一个变量的结果

Flutter 如何避免将一个变量的结果更改为另一个变量的结果,flutter,dart,Flutter,Dart,我有一个变量cart,它是类型为CartItem的购物车项目列表。然后另一个变量选择editem,该变量的类型也是CartItem。当我在购物车中循环并通过比较其ID是否等于所选商品的ID来获取感兴趣的商品时,我会更改其数量。这很好,是意料之中的事。挑战在于它导致selectedItem的数量也在变化。仅更改selectedItem的数量也会更改购物车项目的数量。如果我同时更改这两个参数,则会出现双增量。为什么会发生这种情况,我怎样才能防止这种情况发生。目的是改变这两种情况。很明显,只要改变一个

我有一个变量
cart
,它是类型为
CartItem
的购物车项目列表。然后另一个变量
选择editem
,该变量的类型也是
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
              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();
            }
          }

您正在为您的
selectedCartItem
创建
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);
var cart=List();
var selectedItem=购物车[索引];//其中索引是所选项目的位置
如果你不知道哪一个是,你也可以这样做:

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);
var cart=List();
var selectedItem=cart.singleWhere((item)=>item.product.id==selectedId);

您正在为您的
所选CartItem
创建一个
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);
var cart=List();
var selectedItem=购物车[索引];//其中索引是所选项目的位置
如果你不知道哪一个是,你也可以这样做:

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);
var cart=List();
var selectedItem=cart.singleWhere((item)=>item.product.id==selectedId);

这两个变量很可能引用同一个变量instance@Pavel您可能是对的,但我希望在创建新实例时使用不同的引用。这两个变量很可能引用同一个实例instance@Pavel您可能是对的,但我希望在创建新实例时使用不同的引用我的意图是为selectedCartItem创建一个新实例,因为它是在项目的详细信息页面上选择的,即使它不在购物车中,其数量也可以减少或增加。我的目的是为selectedCartItem创建一个新实例,因为它是在项目的详细信息页面上选择的,即使在它不在车里。