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

2019-02-11 23:53发布

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!

4条回答
The star\"
2楼-- · 2019-02-12 00:54

Late to the party, but I recently faced this problem and had to do something along the lines of :-

RandomObject {

int x;
int y;

RandomObject(int x, int y) {
    this.x = x;
    this.y = y;
}

RandomObject.clone(RandomObject randomObject): super(randomObject.x, randomObject.y);
}

Calling RandomObject.clone seems to do something similar. This can be added to an abstract class so that you can create generic builders of objects.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-12 00:41

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);
查看更多
爷、活的狠高调
4楼-- · 2019-02-12 00:45

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.
查看更多
时光不老,我们不散
5楼-- · 2019-02-12 00:50

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.

查看更多
登录 后发表回答