0

I have this sample code that I write on dartpad, you can run it too :

void main() {
  
  Task a = Task(id: 1, title:'task 1', users: [User(id:0, name:'John')]);
  Task b = Task(id: a.id, title: a.title, users: List<User>.from(a.users!));
  
  resetTask(Task task) {
    b.id = task.id;
    b.title = task.title;
    b.users = List<User>.from(a.users!);
  }
  
  print(b.title); // task 1
  print('${b.users![0].name} \n'); // John
  b.title = 'task 2';
  b.users![0].name = 'Doe';
  print(b.title); // task 2
  print('${b.users![0].name} \n'); // Doe
  resetTask(a);
  print(b.title); // task 1
  print('${b.users![0].name} \n'); // John
  
}

class Task {
  
  Task({this.id, this.title, this.users});
  
  int? id;
  String? title;
  List<User>? users;
}

class User {
  
  User({this.id, this.name});
  
  int? id;
  String? name;
}

What you see on comment is what I'm expecting in output console :

task 1
John

task 2
Doe

task 1
John

And here is my result :

task 1
John 

task 2
Doe 

task 1
Doe 

I don't understand why my user isn't refresh ?

It looks like both user list are linked

rigorousCode
  • 385
  • 1
  • 2
  • 9
  • 1
    You cannot copy list of custom classes that way, you're only copying references, have a look on how to overcome this here: https://stackoverflow.com/questions/13107906/how-can-i-clone-an-object-deep-copy-in-dart – ManuH68 Feb 27 '22 at 14:34
  • Don't repost [the same question](https://stackoverflow.com/questions/71285162/). You can edit your original question if you need to. – jamesdlin Feb 27 '22 at 18:36

0 Answers0