How to copy List in dart without old reference?

后端 未结 7 1496
一个人的身影
一个人的身影 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:30
    List<T>.addall(T) worked for me
    

    i.e.

    List<mylist>.addall(oldlist)
    
    0 讨论(0)
  • 2021-01-17 11:31
    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

    0 讨论(0)
  • 2021-01-17 11:37

    Change it to JSON then parse it again to object. I know it's dirty way.

    (+) it works and less code. (-) it not parsing method.

    0 讨论(0)
  • 2021-01-17 11:42

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

    List<int> source = [1];
    List<int> copied = List.of(source);
    
    0 讨论(0)
  • 2021-01-17 11:42

    I just used thelist2 = thelist1.toList(); and it work

    0 讨论(0)
  • 2021-01-17 11:50

    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);
    }
    
    0 讨论(0)
提交回复
热议问题