Home > OS >  When Modify a Value in the Copied List, It Modify the Value in The Original List Flutter
When Modify a Value in the Copied List, It Modify the Value in The Original List Flutter

Time:11-21

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.

CodePudding user response:

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);
}
  • Related