0
class Record{
  int data;
  Record(this.data);
}

class BigRecord{
  Record record;
  BigRecord(this.record);
}


void main(){
  BigRecord big1 = BigRecord(Record(20));
  BigRecord big = BigRecord(Record(23));
  big1 = big;
  big.record.data=22;
  print(big1.record.data); //22
}

How can I copy the object without just referring to the same location? I just want to pass the value of big to big1. But it passes the location of big. And when I change big it also changes the big1. What can I do to just change big without changing big1?

Passing big.record.data works but that's not what I want. Because this is just a small reference for my issue.

  • All types in Dart are reference types and parameters are passed by value (where the value are a reference to an object). See this answer: https://stackoverflow.com/a/65674480/1953515 – julemand101 May 06 '21 at 12:26

1 Answers1

3

If you want to pass a copy of an object, you must create a copy. Assignment in Dart doesn't create copies, it just passes around references to the same object.

So, add a copy/clone/something method to your class an use it when you need a copy. Make it deep-copy if that's what you need.

class Record{
  int data;
  Record(this.data);
  Record clone() => Record(data);
}
class BigRecord{
  Record record;
  BigRecord(this.record);
  BigRecord clone() => BigRecord(record.clone());
}
void main(){
  BigRecord big1 = BigRecord(Record(20));
  BigRecord big = BigRecord(Record(23));
  big1 = big.clone();
  big.record.data = 22;
  print(big1.record.data); // 23!
}
lrn
  • 64,680
  • 7
  • 105
  • 121