Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...