How to copy List<T> in dart without old reference?

you can use List.from() function. try this code:

//modal for list
class MyModal {
  int myField1;
  String name;
  List<MyModal> adjacentNodes;
  MyModal(this.myField1, this.name) {
    adjacentNodes = new List<MyModal>();
  }
}

void runCopy() {
//pre code
  List<MyModal> originalList = new List<MyModal>();
  originalList.add(new MyModal(1, "firstBuddy"));

//copying list
  List<MyModal> secondList = List.from(originalList);
  secondList.addAll(originalList);
  print(originalList);
  print(secondList);
}

class MyModal {
  int myField1;
  String myField2;
  List<MyModal> adjacentNodes;
  MyModal(this.myField1,this.myField2);

  MyModal.clone(MyModal source) : 
      this.myField1 = source.myField1, 
      this.myField2 = source.myField2,
      this.adjacentNodes = source.adjacentNodes.map((item) => new MyModal.clone(item)).toList();
}

var secondList = originalList.map((item) => new MyModal.clone(item)).toList();

If a member of MyModal is of a non-primitive type like String, int, double, num, bool, then the clone() method needs to clone the instances references point to as well.

I think for your use case using immutable values is a better approach, for example with https://pub.dartlang.org/packages/built_value


Recommended way is to use List.of() constructor.

List<int> source = [1];
List<int> copied = List.of(source);

Tags:

Dart

Flutter