Cloning lists, maps, and sets in Dart

Suragch
6 min readAug 26, 2021

Understanding the difference between deep and shallow copying

Photo by Kelly Sikkema

When you create a collection in Dart, the contents of the collection are mutable. You can see that in the following example:

final myList = ['sheep', 'cow'];
myList.add('horse'); // [sheep, cow, horse]
myList.remove('cow'); // [sheep, horse]
myList[0] = 'goat'; // [goat, horse]

That is all very useful when you want to manipulate the elements of a collection. However, sometimes you want to share a copy of your collection with someone else.

Let’s look at what happens when you “copy” a list by assigning it to a new variable:

final myList = ['sheep', 'cow'];
final yourCopy = myList;
yourCopy.remove('cow');
print(myList); // [sheep]
print(yourCopy); // [sheep]

You removed “your” cow, by now mine is gone, too!

The reason is that all variable names in Dart are just references that ultimately lead to where the object is stored in memory. Assigning one variable name to another copies the reference; it doesn’t make a new copy of the object itself. If I write my email address and password on a piece of paper and give it to you, that doesn’t create a new email account for you; it just gives you access to my account. Dart objects are the same way…

--

--