Dart 有没有办法克隆对象?

Tra*_*ack 4 cloning dart flutter

我在 Stackoverflow 上询问了一些有关此问题的问题,但对我来说没有任何意义。最简单的方法是什么?

小智 9

检查以下类以供参考:

class Customer {
  final String id;
  final String name;
  final String address;
  final String phoneNo;
  final String gstin;
  final String state;

Customer({
    this.id = '',
    @required this.name,
    @required this.address,
    @required this.phoneNo,
    this.gstin,
    @required this.state,
  });

  Customer copyWith({
    String name,
    String address,
    String phoneNo,
    String gstin,
    String state,
  }) {
    return Customer(
      name: name ?? this.name,
      address: address ?? this.address,
      phoneNo: phoneNo ?? this.phoneNo,
      gstin: gstin ?? this.gstin,
      state: state ?? this.state,
    );
  }

}
Run Code Online (Sandbox Code Playgroud)

使用 copyWith 构造函数,您可以创建对象的副本。

如果您不将任何参数传递给 copyWith 构造函数,它将返回具有相同值的新对象

但是,如果您希望更改使用 copyWith 构造函数执行的任何参数,它将返回带有您传递的新参数值的对象副本

注意:在 copyWith 构造函数中,假设如果更改一个参数值,则其他参数值保持与第一个对象相同。