Its been long time i am suffering between byVal and byRef in dart…
To make myself more clear i have created this demo to explain what i am suffering
I want simply copy of a list and than want to make changes in new list but keeping in mind that original list should be unchanged…
in following program i need to get output like
users =['A','B','C','D']
friends=['AA','BB'];
templist=['AAA','BBB']
but i am getting
users =['AAA','BBB','C','D']
friends =['AAA','BBB'];
templist =['AAA','BBB']
void main() {
List<User> users = [
User(name: 'A', age: '43'),
User(name: 'B', age: '12'),
User(name: 'C', age: '53'),
User(name: 'D', age: '22'),
];
List<User> friends = [];
List<User> templist = [];
final u1 = users[0];
friends.add(u1);
friends[0].name = 'AA';
final p2 = users[1];
friends.add(p2);
friends[1].name = "BB";
templist = List.from(friends);
templist[0].name = "AAA";
templist[1].name = "BBB";
for (var u in users) {
print(u.name);
}
for (var f in friends) {
print(f.name);
}
for (var t in templist) {
print(t.name);
}
}
2
Answers
You need to make copies of the users when filling the other lists.
Assuming that your
User
class is something like thisyou could add a
copy
function to it likeAnd then your final code could be something like this
By the way. It’s very common that your data classes are more complicated but have some kind of
toJson
andfromJson
functions. In that case an easy way to make a copy is to call them back to back. So likein your code…
u are not creating copy but making reference to a list…
like templist=friends
that statement do not mean that you are creating new duplicate list but both templist and friends are refering to same list…
for single object..
here both x and y refering to same object
so to make copy
and for a list of user
to make copy u need to code as below
add method to class
try this code..it will give u same output that u want