首页 > 解决方案 > 有没有办法在 Dart 中克​​隆对象?

问题描述

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

标签: flutterdartcloning

解决方案


检查以下类以供参考:

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

}

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

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

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

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


推荐阅读