Home > Software engineering >  How to use copyWith() for nested objects
How to use copyWith() for nested objects

Time:09-14

I have a company which can contain multiple customers and therefore is nested. The company class as well as the customer class contain both copyWith() functions.

I realized that if I copy a company object with the copyWith() function that the customer list is NOT copied as well and still references the original customer list.

Later in the code, it is possible to accidentally change the original customer list.

How do I write a copyWith() function that copies the company AND the nested customers as well?

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,
      customers: customers ?? this.customers,
    );
  }
}
class Customer {
  final String name;

  const Customer({required this.name});

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

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");

  /// Here I only wanted to change the companyCopy but... 
  companyCopy = companyCopy.copyWith(customers: customers);

  print(companyCopy.customers[0].name);
  /// ... the original company changes as well! 
  print(company.customers[0].name);

}

Output:

Customer 1
Customer 1
Customer 3
Customer 3

CodePudding user response:

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,
      customers: customers!=null ? List.from(customers) : List.from(this.customers),
    );
  }
}
  • Related