I have a list of objects that hold some user input.
What I want to achieve: Duplicating the list before resetting the objects to their default values, so I don't lose the information.
The problem: No matter what I try, whenever I modify objects in list_1, the objects in list_2 are being modified as well; overwriting the data I want to keep that way.
Attempts at solving it:
I tried declaring the second lists in all kinds of ways:
list_2 = list_1;
list_2 = List.of(list_1);
list_2 = [...list_1);
list_2 = list_1.toList();
No luck. I then tried this:
list_2=[];
for (var i in list_1){
list_2.add(i);}
Still, the same behaviour. If I modify a value of an object in list_1, the corresponding object in list_2 is changed as well.
I'm confused. Am I only creating new references to the objects, but not actually multiplying them? How would I go about changing that? Is something else going on? THANKS!
List.of(list_1),[...list_1], andlist1.toList()will all duplicatelist_1but not the contained objects. An answer to your question depends on what those objects are, and you haven't specified what objects yourLists contain.list_1and build a newList, invoking an appropriate constructor of your class for each element. Adding aclone()method to your class can make it easier, but you would need to take care to override it appropriately in any derived classes.