Home > front end >  How to preserve data after flutter List.add() in flutter
How to preserve data after flutter List.add() in flutter

Time:12-16

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();

CodePudding user response:

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]]

CodePudding user response:

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); // []
}

CodePudding user response:

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
}
  • Related