How to make change copy data of RxList without effect to orignal data?

Viewed 25

I am facing an issue when update a copy RxList and modify some field then original data also change.

Please you help me, how to make change without effect to the original data? This mean that, when I click on checkBox then copyList elemnt change to TRUE and not affect to drniks list but current it changes both.
#mock data

List<Drink> drinks = [
  Drink(id: 0, name: "Coca Cola",isChecked: false),
  Drink(id: 1, name: "Milk",isChecked: false),
  Drink(id: 2, name: "Soda",isChecked: false),
];

I want to build a checkbox by listing these above mock data

var drinkIds = <int>[];
var copyList = drinks;
@override
  Widget build(BuildContext context) {
  return Obx(()=>ListView.builder(
  shrinkWrap: true,
  physics: const NeverScrollableScrollPhysics(),
  padding: EdgeInsets.zero,
  itemCount: copyList.length;
  itemBuilder:(_,index)=>ListTitle(
    minLeadingWidth: 10,
    visualDensity: VisualDensity(vertical: -4),
    contentPadding: EdgeInsets.zero,
    title: Text("${copyList[index].title}"),
    leading: copyList[index].isChecked ? Icon(Icons.check_box_outlined, color: primaryColor) : Icon(Icons.check_box_outline_blank, color: Colors.grey),
    onTap: () {
       copyList[index].isChecked = !copyList[index].isChecked;
       if (copyList[index].isChecked) {
          drinkIds.add(copyList[index].id);
       } else {
         drinkIds.removeWhere((element) => element == copyList[index].id);
        }
      copyList.refresh();
   },
    
  )
  
  ));
 
}
1 Answers

You can copy list by spread operators

List newList = [...drinks];
Map newMap = {...myMap}; // this is same for maps

The newList is copy of drinks and now you can work with it without effects on original

Related