0

I want to copy list and make no reference even when I edit value in copied list. I tried addAll(), List.from(), map(), toList() and [...myList] but they were unhelpful.

Edit for Clarification

Ex:

class Item{
    String description;
    int price; 

    Item(this.description, this.price);
    }

List<Item> items = [
Item('item 1', 100),
Item('item 2', 200),
Item('item 3', 300),
];

List<Item> selectedItems = List.from(items);

When I edit selectedItems original list items shouldn't be affected, but it's not?!

selectedItems[0].price = 115;

it modifies the price of element 0 in both.

mhmd
  • 395
  • 4
  • 19

1 Answers1

0

Flutter haven't copy function for objects, you should create "copy constructor" manually. It's discussed here: How can I clone an Object (deep copy) in Dart?

Solution for your example:

void main() {
  // Original list
  List<Item> items = [
    Item('item 1', 100),
    Item('item 2', 200),
    Item('item 3', 300),
  ];

  // Copied list
  List<Item> selectedItems = items.map((it) => Item.copy(it)).toList();

  // Change price for item in copied list
  selectedItems[0].price = 115;

  print("Original list:");
  items.forEach((it) => print("Description: ${it.description}, price: ${it.price}"));

  print("Copied list:");
  selectedItems.forEach((it) => print("Description: ${it.description}, price: ${it.price}"));
}

class Item {
  String description;
  int price;

  Item(this.description, this.price);

  // Copied constructor
  Item.copy(Item item) : this(item.description, item.price);
}
Andrei R
  • 1,433
  • 2
  • 10
  • 16
  • I am using this already, is there different `Item copyWith() => Item(this.description, this.price);` – mhmd Nov 21 '21 at 05:18
  • It works with delete some elements inside copied list it does not deletes from original list but when I edit not works? – mhmd Nov 21 '21 at 05:24
  • ok it works with both ways just I am not using `items.map((it) => Item.copy(it)).toList();` when defining selectedList. Thank you :) – mhmd Nov 21 '21 at 05:33