102

是否有语言支持的方式在 Dart 中制作对象的完整(深度)副本?

仅次要;有多种方法可以做到这一点,有什么区别?

感谢您的澄清!

4

16 回答 16

51

Darts 内置集合使用名为“from”的命名构造函数来完成此操作。请参阅这篇文章:在 Dart 中克​​隆列表、地图或集合

Map mapA = {
    'foo': 'bar'
};
Map mapB = new Map.from(mapA);
于 2015-02-17T03:26:11.783 回答
37

就未解决的问题似乎暗示而言,没有:

http://code.google.com/p/dart/issues/detail?id=3367

特别是:

.. Objects have identity, and you can only pass around references to them. There is no implicit copying.
于 2012-10-28T10:19:50.627 回答
27

派对迟到了,但我最近遇到了这个问题,不得不按照以下方式做一些事情:-

class RandomObject {

  RandomObject(this.x, this.y);

  RandomObject.clone(RandomObject randomObject): this(randomObject.x, randomObject.y);

  int x;
  int y;
}

然后,您可以使用原件调用副本,如下所示:

final RandomObject original = RandomObject(1, 2);
final RandomObject copy = RandomObject.clone(original);
于 2019-01-10T20:48:09.400 回答
15

我猜对于不太复杂的对象,您可以使用转换库:

import 'dart:convert';

然后使用 JSON 编码/解码功能

Map clonedObject = JSON.decode(JSON.encode(object));

如果您使用自定义类作为要克隆的对象中的值,则该类需要实现 toJson() 方法,或者您必须为 JSON.encode 方法提供 toEncodable 函数,并为解码调用提供 reviver 方法.

于 2014-10-28T18:41:59.070 回答
9

不幸的是没有语言支持。我所做的是创建一个名为的抽象类Copyable,我可以在我希望能够复制的类中实现它:

abstract class Copyable<T> {
  T copy();
  T copyWith();
}

然后我可以按如下方式使用它,例如用于 Location 对象:

class Location implements Copyable<Location> {
  Location({
    required this.longitude,
    required this.latitude,
    required this.timestamp,
  });

  final double longitude;
  final double latitude;
  final DateTime timestamp;

  @override
  Location copy() => Location(
        longitude: longitude,
        latitude: latitude,
        timestamp: timestamp,
      );

  @override
  Location copyWith({
    double? longitude,
    double? latitude,
    DateTime? timestamp,
  }) =>
      Location(
        longitude: longitude ?? this.longitude,
        latitude: latitude ?? this.latitude,
        timestamp: timestamp ?? this.timestamp,
      );
}
于 2020-03-27T19:32:16.543 回答
8

要在没有引用的情况下复制对象,我找到的解决方案类似于此处发布的解决方案,但是如果对象包含 MAP 或 LIST,您必须这样做:

class Item {
  int id;
  String nome;
  String email;
  bool logado;
  Map mapa;
  List lista;
  Item({this.id, this.nome, this.email, this.logado, this.mapa, this.lista});

  Item copyWith({ int id, String nome, String email, bool logado, Map mapa, List lista }) {
    return Item(
      id: id ?? this.id,
      nome: nome ?? this.nome,
      email: email ?? this.email,
      logado: logado ?? this.logado,
      mapa: mapa ?? Map.from(this.mapa ?? {}),
      lista: lista ?? List.from(this.lista ?? []),
    );
  }
}
Item item1 = Item(
    id: 1,
    nome: 'João Silva',
    email: 'joaosilva@gmail.com',
    logado: true,
    mapa: {
      'chave1': 'valor1',
      'chave2': 'valor2',
    },
    lista: ['1', '2'],
  );

// -----------------
// copy and change data
Item item2 = item1.copyWith(
    id: 2,
    nome: 'Pedro de Nobrega',
    lista: ['4', '5', '6', '7', '8']
  );

// -----------------
// copy and not change data
Item item3 = item1.copyWith();

// -----------------
// copy and change a specific key of Map or List
Item item4 = item1.copyWith();
item4.mapa['chave2'] = 'valor2New';

查看 dartpad 上的示例

https://dartpad.dev/f114ef18700a41a3aa04a4837c13c70e

于 2020-05-30T02:24:04.650 回答
5

假设你有课

Class DailyInfo

  { 
     String xxx;
  }

通过创建类对象 dailyInfo 的新克隆

 DailyInfo newDailyInfo =  new DailyInfo.fromJson(dailyInfo.toJson());

为此,您的班级必须已实施

 factory DailyInfo.fromJson(Map<String, dynamic> json) => _$DailyInfoFromJson(json);


Map<String, dynamic> toJson() => _$DailyInfoToJson(this);

这可以通过使用使类可序列化来完成

@JsonSerializable(fieldRename: FieldRename.snake, includeIfNull: false)
Class DailyInfo{ 
 String xxx;
}
于 2019-07-25T17:30:07.093 回答
4

尝试使用 Dart 提供的Copyable接口。

于 2020-01-22T01:34:12.167 回答
4

它仅适用于可以由 JSON 表示的对象类型。

ClassName newObj = ClassName.fromMap(obj.toMap());

或者

ClassName newObj = ClassName.fromJson(obj.toJson());
于 2020-01-17T08:02:29.067 回答
3

没有内置的深度克隆对象的方法 - 您必须自己提供方法。

我经常需要从 JSON 编码/解码我的类,所以我通常提供MyClass fromMap(Map)Map<String, dynamic> toJson()方法。这些可用于创建深度克隆,方法是首先将对象编码为 JSON,然后将其解码回来。

但是,出于性能原因,我通常会实现一个单独的clone方法。这是几分钟的工作,但我发现它通常是值得花时间的。

在下面的示例中,cloneSlow使用 JSON 技术,并cloneFast使用显式实现的克隆方法。打印输出证明该克隆确实是一个深度克隆,而不仅仅是引用的副本a

import 'dart:convert';

class A{
  String a;
  A(this.a);
  
  factory A.fromMap(Map map){
    return A(
        map['a']
   );
  }
  
  Map<String, dynamic> toJson(){
    return {
      'a': a
    };
  }
  
  
  A cloneSlow(){
    return A.fromMap(jsonDecode(jsonEncode(this)));
  }

  A cloneFast(){
    return A(
      a
    );
  }
  
  
  @override
  String toString() => 'A(a: $a)';
}

void main() {
  A a = A('a');
  A b = a.cloneFast();
  b.a = 'b';
  
  print('a: $a   b: $b');
}




于 2020-12-30T09:07:39.770 回答
2

有一个更简单的方法来解决这个问题...,例如使用运算符,克隆一个 Map

Map p = {'name' : 'parsa','age' : 27};
Map n = {...p};

此外,您可以对类属性执行此操作。就我而言,我需要克隆一个类的列出属性。所以:

class P1 {
List<String> names = [some data];
}

/// codes
P1 p = P1();
List<String> clonedList = [...p.names]
// now clonedList is an unreferenced type
于 2021-11-10T14:16:29.767 回答
1

//希望这个工作

 void main() {
  List newList = [{"top": 179.399, "left": 384.5, "bottom": 362.6, "right": 1534.5}, {"top": 384.4, "left": 656.5, "bottom": 574.6, "right": 1264.5}];
  List tempList = cloneMyList(newList);
  tempList[0]["top"] = 100;
  newList[1]["left"] = 300;
  print(newList);
  print(tempList);
}

List cloneMyList(List originalList) {
 List clonedList = new List();
  for(Map data in originalList) {
    clonedList.add(Map.from(data));
  }
  return clonedList;
}
于 2020-12-07T08:44:28.553 回答
1

参考@Phill Wiggins 的回答,这是一个带有 .from 构造函数和命名参数的示例:

class SomeObject{
  String parameter1;
  String parameter2;

  // Normal Constructor
  SomeObject({
    this.parameter1,
    this.parameter2,
  });

  // .from Constructor for copying
  factory SomeObject.from(SomeObject objectA){
    return SomeObject(
      parameter1: objectA.parameter1,
      parameter2: objectA.parameter2,
    );
  }

}

然后,在要复制的位置执行此操作:

SomeObject a = SomeObject(parameter1: "param1", parameter2: "param2");
SomeObject copyOfA = SomeObject.from(a);
于 2021-05-28T10:00:58.833 回答
0

make a helper class:

class DeepCopy {
  static clone(obj) {
    var tempObj = {};
    for (var key in obj.keys) {
      tempObj[key] = obj[key];
    }
    return tempObj;
  }
}

and copy what you want:

 List cloneList = [];
 if (existList.length > 0) {
    for (var element in existList) {
        cloneList.add(DeepCopy.clone(element));
    }
 }
于 2021-01-07T02:40:49.623 回答
0

比方说,你想深拷贝一个对象Person,它的属性是其他对象的列表Skills。按照惯例,我们使用copyWith带有可选参数的方法进行深拷贝,但您可以将其命名为任何您想要的名称。

你可以做这样的事情

class Skills {
  final String name;

  Skills({required this.name});

  Skills copyWith({
    String? name,
  }) {
    return Skills(
      name: name ?? this.name,
    );
  }
}

class Person {
  final List<Skills> skills;

  const Person({required this.skills});

  Person copyWith({
    List<Skills>? skills,
  }) =>
      Person(skills: skills ?? this.skills.map((e) => e.copyWith()).toList());
}

请记住,仅使用this.skills只会复制列表的引用。所以原始对象和复制的对象将指向相同的技能列表。

  Person copyWith({
    List<Skills>? skills,
  }) =>
      Person(skills: skills ?? this.skills);

如果您的列表是原始类型,您可以这样做。原始类型会自动复制,因此您可以使用这种较短的语法。

class Person {
  final List<int> names;

  const Person({required this.names});

  Person copyWith({
    List<int>? names,
  }) =>
      Person(names: names ?? []...addAll(names));
}
于 2021-08-05T18:39:40.327 回答
0

dart 中的 Deep Copy 示例。

void main() {
  Person person1 = Person(
      id: 1001,
      firstName: 'John',
      lastName: 'Doe',
      email: 'john.doe@email.com',
      alive: true);

  Person person2 = Person(
      id: person1.id,
      firstName: person1.firstName,
      lastName: person1.lastName,
      email: person1.email,
      alive: person1.alive);

  print('Object: person1');
  print('id     : ${person1.id}');
  print('fName  : ${person1.firstName}');
  print('lName  : ${person1.lastName}');
  print('email  : ${person1.email}');
  print('alive  : ${person1.alive}');
  print('=hashCode=: ${person1.hashCode}');

  print('Object: person2');
  print('id     : ${person2.id}');
  print('fName  : ${person2.firstName}');
  print('lName  : ${person2.lastName}');
  print('email  : ${person2.email}');
  print('alive  : ${person2.alive}');
  print('=hashCode=: ${person2.hashCode}');
}

class Person {
  int id;
  String firstName;
  String lastName;
  String email;
  bool alive;
  Person({this.id, this.firstName, this.lastName, this.email, this.alive});
}

以及下面的输出。

id     : 1001
fName  : John
lName  : Doe
email  : john.doe@email.com
alive  : true
=hashCode=: 515186678

Object: person2
id     : 1001
fName  : John
lName  : Doe
email  : john.doe@email.com
alive  : true
=hashCode=: 686393765
于 2020-11-17T01:45:41.907 回答