How to copy List in dart without old reference?

后端 未结 7 1499
一个人的身影
一个人的身影 2021-01-17 11:14

Code will explain all:

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


        
7条回答
  •  说谎
    说谎 (楼主)
    2021-01-17 11:31

    class MyModal {
      int myField1;
      String myField2;
      List 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

提交回复
热议问题