I try to modify an object:
void main() {
Model item = Model(list: [3,4]);
print(item.list);
Model test = item;
List modifyList = test.list!;
modifyList[0] = 999;
test = Model(list: modifyList);
print("original: " + item.list.toString());
print("modified: " + test.list.toString());
}
class Model {
String? title;
String? postid;
List? list;
Model({
this.title,
this.postid,
this.list,
});
}
this prints:
[3, 4]
original: [999, 4]
modified: [999, 4]
I dont understand why the first parameter of the original test model is also modified. How can I modify only the test model and keep the original?
Whats the reason for modifying the original variable even though I have previously put it to the new test?
2
Answers
I ended up to adapted the copyWith from @Jason and added List.from to clone the list and remove the reference:
output:
clone list without reference: https://stackoverflow.com/a/71031170/3037763
other way is
.toList()
: https://stackoverflow.com/a/62013491/3037763You can’t do this cause it’s references to original object
Try to deep copy change the value
output: