Dart How to Copy/Clone a List
It is easy to clone or copy a list in Dart. You probably don’t want to just assign your existing list to a new variable. This would just create a reference to the original. Changing one would affect the other. Chances are you want a completely new copy so that each list can be modified independently of the other. To do this you need to create a copy as shown here.
Here are five different ways to copy or clone a list:
List a = ['x','y', 'z']; // original list var b = [...a]; var c = List.from(a); var d = List.of(a); var e = List.generate(a.length, (index) => a[index]); var f = List.unmodifiable(a);
You can test out modifying these lists. This will show that they are each a completely new clone and not just a reference to the original.
a = 'm'; b = 'n'; c = 'o'; d = 'p'; e = 'q'; //f = 'r'; // can't modify
We can then verify the contents and type for each of our new lists.
print(a.runtimeType); print(b.runtimeType); print(c.runtimeType); print(d.runtimeType); print(e.runtimeType); print(f.runtimeType); print(a); print(b); print(c); print(d); print(e); print(f);
Assign One List to Another ( Reference )
This is probably not what you want. It just creates a pointer/reference to the original list.
If you just assign one list to another it doesn’t actually create a separate copy. Both variables are really just different names for the same list. They point to the exact same data. Changing the elements in one list will also change the elements in the other.
var a = [1, 2, 3]; var b = a; print(a); print(b); a = 5; // change the first list print(a); print(b); // second list was updated too