Search code examples
flutterdartcopyclone

In Dart, how can copy/clone a 2D list?


I have 2 two dimensional lists declared as following, what is the correct and fast way to copy/clone a 2 dimensional list (I to N) in Dart?

List<List<double>>? I = List.generate(
        3, (i) => List.generate(1000 * 1000, (j) => 0.0, growable: false),
        growable: false);
 List<List<double>>? N = List.generate(
        3, (i) => List.generate(1000 * 1000, (j) => 0.0, growable: false),

I can loop through each element and copy it but that's not the efficient way to do it.

for (int i = 0; i < I!.length; i++)
      for (int j = 0; j < I![i].length; j++) N![i][j] = I![i][j];

Solution

  • List List.copyRange(List target, int at, List source, [int? start, int? end])

    list.setRange(int start, int end, Iterable iterable, [int skipCount = 0])

    for (int i = 0; i < I!.length; i++)
        List.copyRange<int>(N![i], 0, I![i])
    
    for (int i = 0; i < I!.length; i++)
        N![i].setRange<int>(0, N![i].length,I![i])
    

    This will reset the item pointer

    List.copyRange(N!,0, I!.map<List<int>>((item)=>item.toList()).toList());