Dart: Copy with Constructor

Dart: Copy with Constructor

ยท

2 min read

In Dart, the copyWith constructor is a convenient way to create a new object by copying an existing one and making some modifications to its properties. This is often used with immutable classes, where the properties cannot be changed directly after the object is created.

Let's break it down with a simple example:

// Define an immutable class with a copyWith constructor
class Person {
  final String name;
  final int age;

  // Constructor
  Person({required this.name, required this.age});

  // CopyWith constructor
  Person copyWith({String? name, int? age}) {
    return Person(
      name: name ?? this.name,
      age: age ?? this.age,
    );
  }
}

void main() {
  // Create an instance of the Person class
  var person1 = Person(name: "Alice", age: 25);

  // Use the copyWith constructor to create a new instance with modifications
  var person2 = person1.copyWith(name: "Bob");

  // Print the original and modified objects
  print("Original Person: ${person1.name}, ${person1.age} years old");
  print("Modified Person: ${person2.name}, ${person2.age} years old");
}

Explanation:

  • The Person class has two properties: name and age. They are marked as final, making the class immutable.

  • The class has a regular constructor that initializes the properties.

  • The copyWith constructor takes optional parameters (name and age) and returns a new instance of Person with the specified modifications. If no modifications are provided, it returns a copy of the original object.

  • In the main function, an original Person object (person1) is created with the name "Alice" and age 25.

  • The copyWith constructor is then used to create a new Person object (person2) with a modified name ("Bob"). The age remains the same since it was not specified.

Using copyWith is a clean and efficient way to create modified versions of immutable objects, especially in scenarios where you want to keep the original object unchanged.

Did you find this article valuable?

Support Vinit Mepani (Flutter Developer) by becoming a sponsor. Any amount is appreciated!

ย