Is there a Language supported way make a full (deep) copy of an Object in Dart?
Secondary only; are there multiple ways of doing this, and what are the differences?<
No as far as open issues seems to suggest:
http://code.google.com/p/dart/issues/detail?id=3367
And specifically:
.. Objects have identity, and you can only pass around references to them. There is no implicit copying.
Let's say you a have class
Class DailyInfo
{
String xxx;
}
Make a new clone of the class object dailyInfo by
DailyInfo newDailyInfo = new DailyInfo.fromJson(dailyInfo.toJson());
For this to work your class must have implemented
factory DailyInfo.fromJson(Map<String, dynamic> json) => _$DailyInfoFromJson(json);
Map<String, dynamic> toJson() => _$DailyInfoToJson(this);
which can be done by making class serializable using
@JsonSerializable(fieldRename: FieldRename.snake, includeIfNull: false)
Class DailyInfo{
String xxx;
}
I guess for not-too-complex objects, you could use the convert library:
import 'dart:convert';
and then use the JSON encode/decode functionality
Map clonedObject = JSON.decode(JSON.encode(object));
If you're using a custom class as a value in the object to clone, the class either needs to implement a toJson() method or you have to provide a toEncodable function for the JSON.encode method and a reviver method for the decode call.
Late to the party, but I recently faced this problem and had to do something along the lines of :-
class RandomObject {
RandomObject(this.x, this.y);
RandomObject.clone(RandomObject randomObject): this(randomObject.x, randomObject.y);
int x;
int y;
}
Then, you can just call copy with the original, like so:-
final RandomObject original = RandomObject(1, 2);
final RandomObject copy = RandomObject.clone(original);
You could use the equatable library https://pub.dev/packages/equatable It allows for equating different instances of the same class provided they extend the Equatable class.