Reputation: 441
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!
Upvotes: 1
Views: 2503
Reputation: 286
this happen to me while aago with objects
I fixed it by converting the object to json format then asign the new object from the json data with the method from the model fromJson(json) that worked fine
in case of the list there is an easier way
main() {
List<int> x = [1, 2];
List<int> y = [];
x.map((e) => y.add(e)).toList();
print(x.toString()); //[1, 2]
y[0]++;
print(y.toString()); //[2, 2]
print(x.toString()); //[1, 2]
}
Upvotes: 0
Reputation: 905
Try this one:
Created a demo list:
List<Status> statuses = <Status>[
Status(name: 'Confirmed', isCheck: true),
Status(name: 'Cancelled', isCheck: true),
];
List<Status> otherStatuses = statuses.map((status)=>Status(name:status.name, isCheck:status.isCheck)).toList()
Upvotes: 1