How can I clone an Object (deep copy) in Dart?

こ雲淡風輕ζ 提交于 2019-11-30 07:20:32

问题


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?

Thanks for clarification!


回答1:


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.



回答2:


Darts built-in collections use a named constructor called "from" to accomplish this. See this post: Clone a List, Map or Set in Dart

Map mapA = {
    'foo': 'bar'
};
Map mapB = new Map.from(mapA);



回答3:


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.




回答4:


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);



回答5:


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;
}


来源:https://stackoverflow.com/questions/13107906/how-can-i-clone-an-object-deep-copy-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!