listflutterdartflutter-onpressed

Making a new list from existing list in flutter; changes both list upon action on new list


i am making a list in flutter from an existing list and when i used this new list and perform some action on it like change its quantity parameter it changes the parameter of existing list also. Can some one tell me where i am going wrong.

Existing list:

  List<ItemsModel> originalList=[
    ItemsModel(name: 'High Quality Double Spring Tummy Trimmer For Unisex',quantity: '30'),
    ItemsModel(name: 'High Quality Double Spring Tummy Trimmer For Unisex',quantity: '30'),
    ItemsModel(name: 'High Quality Double Spring Tummy Trimmer For Unisex',quantity: '30'),
  ];

New list:

  List<ItemsModel> updatedItemList;
      void initState() {
        updatedItemList=[];
        originalList.forEach((val){
      updatedItemList.add(val);
    });
        super.initState();
      }

on pressed button:

 updatedItemList[i].quantity=qtyReceive

And on some button pressed i am performing this action that was updating both lists. Why??


Solution

  • As @jamesdlin mentioned, creating a deep copy will solve the issue by change reference to new ItemsModel objects in the list.

    Small example of creating deep copy:

    class ItemsModel{
      String name;
      String quantity;
      ItemsModel({this.name,this.quantity});
    }
    
    
    void main() {
       List<ItemsModel> originalList=[
        ItemsModel(name: 'High Quality Double Spring Tummy Trimmer For Unisex',quantity: '30'),
        ItemsModel(name: 'High Quality Double Spring Tummy Trimmer For Unisex',quantity: '30'),
        ItemsModel(name: 'High Quality Double Spring Tummy Trimmer For Unisex',quantity: '30'),
      ];
    
      List<ItemsModel> updatedItemList;
      updatedItemList=[];
      originalList.forEach((val){
          //creating new ItemsModel objects and adding to the updatedList
          updatedItemList.add(ItemsModel(name:val.name,quantity:val.quantity));
        });
    
      print('Original List');
      for(var listItem in originalList){
        listItem.quantity = '60';
        print('${listItem.name},${listItem.quantity}');
      }
    
      print('Updated List');
        for(var listItem in updatedItemList){
        print('${listItem.name},${listItem.quantity}');
      }
    }