You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Dart嵌套对象编写实现深拷贝的copyWith()方法

解决Dart嵌套结构copyWith浅拷贝导致原对象被修改的问题

你的问题根源在于浅拷贝:原Company类的copyWith方法中,当没有传入customers参数时,直接复用了原对象的customers列表引用,导致拷贝后的Company和原对象共享同一个客户列表。修改拷贝对象的列表元素时,原对象的列表也会被改变。

要实现深拷贝,需要在copyWith中:

  • 为客户列表创建新的实例,避免引用复用
  • 对列表中的每个Customer对象也调用其copyWith方法,完成嵌套对象的拷贝

修改后的Company类代码如下:

class Company {
  final String name;
  final List<Customer> customers;

  const Company({required this.name, required this.customers});

  Company copyWith({
    String? name,
    List<Customer>? customers,
  }) {
    return Company(
      name: name ?? this.name,
      // 深拷贝客户列表:创建新列表,同时拷贝每个Customer对象
      customers: customers?.map((customer) => customer.copyWith()).toList() 
          ?? this.customers.map((customer) => customer.copyWith()).toList(),
    );
  }
}

Customer类的copyWith无需修改,因为它只有不可变的String成员,本身就是值类型拷贝。

现在运行修改后的main函数:

void main() {
  Company company = Company(name: 'Company', customers: [
    Customer(name: 'Customer 1'),
    Customer(name: 'Customer 2'),
  ]);

  Company companyCopy = company.copyWith(name: "Company 2");

  print(company.customers[0].name);
  print(companyCopy.customers[0].name);

  List<Customer> customers = companyCopy.customers;
  customers[0] = Customer(name: "Customer 3");

  companyCopy = companyCopy.copyWith(customers: customers);

  print(companyCopy.customers[0].name);
  print(company.customers[0].name);
}

输出结果:

Customer 1
Customer 1
Customer 3
Customer 1

可以看到,修改拷贝后的companyCopy的客户列表,原company的客户列表不再受到影响。

内容的提问来源于stack exchange,提问作者Philipp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:01:05