Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

Code will explain all:

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

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

//copying list
List<MyModal> secondList = new List<MyModal>();
secondList.addAll(originalList);

//Modifing copy list
secondList.adjacentNodes.add(new MyModal(2,"anotherBuddy"));

//Also modifies original list
print(originalList[0].childs.length); //prints 1, it should prints 0

How can I perform changes in the second list without affecting the original list?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...