Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use copyWith() for nested objects

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading