Reputation: 6082
Getting wired issue like main array has been changed if changed value of another array. I think issue is about copying same address, not sure but just thinking of it. I have tried from last 3 hours but unable to get rid from it.
Look at below illustration to get better idea.
List<page> _pageList;
List<page> _orderList = [];
_pageList = _apiResponse.result as List<page>;
_orderList.add(_pageList[0].element);
_orderList[0].title = "XYZ"
//--> Here if I change the `_orderList[0].title` then it also change the `title` inside "_pageList"
How can we prevent the changes in main array?
Upvotes: 2
Views: 1614
Reputation: 47069
I got same issue in my one of the project. What I have done is, use json
to encode and decode object that help you to make copy of the object so that will not be affected to the main List.
After 3rd line of your code, make changes like below
Elements copyObject = Elements.fromJson(_pageList[0].element.toJson());
// First of all you have to convert your object to the Map and and map to original object like above
_orderList.add(copyObject);
Hope that will help you.
Upvotes: 2
Reputation: 96
You can use a getter function to create a copy of your list and use that instead of altering your actual list. example:
List<Page> get orderList{
return [..._orderList];
}
Upvotes: 3
Reputation: 1385
Lists in Dart store references for complex types, so this is intended behaviour.
From your code:
_orderList.add(_pageList[0].element);
_orderList[0]
and _pageList[0].element
point to the same reference (if they are non-primitive).
There is no general copy()
or clone()
method in dart, as far as i know. So you need to copy the object yourself, if you want a separate instance. (see this question)
Upvotes: 1