0

I want to copy the elements of a 2D list into another list. Let the source list be List<List<int>> source, and the list to which I'm going to copy the elements into be List<List<int>> copied. And when I did-


void main() {
  List<List<int>> source = [
    [1],
    [2],
    [3]
  ];

  List<List<int>> copied = List.from(source);

  copied[2].add(5);

  print(source);
  print(copied);
}

The output came as-

[[1], [2], [3, 5]]
[[1], [2], [3, 5]]

The output I expected was-

[[1], [2], [3]]
[[1], [2], [3, 5]]

The source list seems to have been udpated, when I added 5 into copied . However, when I add a new list into copied, as such-

void main() {
  List<List<int>> source = [
    [1],
    [2],
    [3]
  ];

  List<List<int>> copied = List.from(source);

  copied.add([4]);

  print(source);
  print(copied);
}

The output is as expected-

[[1], [2], [3]]
[[1], [2], [3], [4]]

How do I make it so that all the elements are copied, without actually updating the source list? Thanks, in advance!

Air Admirer
  • 308
  • 2
  • 10
  • 2
    [There is no built-in way to create a deep copy of an object](https://stackoverflow.com/a/13107999/). Your use of `List.from` (which, incidentally, [is not recommended](https://dart.dev/guides/language/effective-dart/usage#dont-use-listfrom-unless-you-intend-to-change-the-type-of-the-result)) creates a *shallow* copy of the outer `List`. If you want deep copies, you should iterate over the members and create new `List`s manually. In your case, you could do `var copied = [for (var row in source) [...row]];`. – jamesdlin May 07 '22 at 06:32

0 Answers0