skip to Main Content

Store data in a 1-dimensional List and add() it to a 2-dimensional List.
After add(), .clear() the one-dimensional List.

However, since List refers to an address, clear() loses the address, so the 2D array becomes an empty List. Is there a way to keep the values ​​in a 2D List even after clearing?

List<int> num = [1, 2, 3];
List<List<int> num2 = [];
num2.add(num);
num.clear();

3

Answers


  1. You could use List.from() to perform shallow copy

    List<int> num = [1, 2, 3];
    List<List<int>> num2 = [];
    num2.add(List.from(num));
    print(num2); //[[1, 2, 3]]
    num.clear();
    print(num2); //[[1, 2, 3]]
    
    Login or Signup to reply.
  2. use trick with toList() method

    void main() {
      List<int> num1 = [1, 2, 3];
      List<List<int>> num2 = [[0,2]] ;
      num2.add(num1.toList());
      num1.clear();
    
      print(num2); // [[0, 2], [1, 2, 3]]
    
      print(num1); // []
    }
    
    Login or Signup to reply.
  3. You should add list as anonymous list

    List<int> num = [1, 2, 3];
    List<List<int>> num2 = [];
    
    // add as anonymous list
    num2.add(num.toList());
    
    num.clear();
    
    print(num2.length);              // 1
    print(num.length);               // 0
          
    for (var element in num2) {
         print(element.length);      // 3
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search