Copying and cloning

suggest change

In Dart, all variables store references to objects. Assigning one variable to another (b = a) does not create a copy—it merely creates a new reference pointing to the same instance in memory. When you need independent duplicates, you must explicitly copy or clone the object.

Shallow Copying Collections

A shallow copy duplicates the container structure (the List, Set, or Map), but the elements inside still refer to the original object references.

Lists

Dart provides several ways to shallow copy a List:

void main() {
  final original = [1, 2, 3];

  // 1. Spread operator (idiomatic)
  final copy1 = [...original];

  // 2. List.of (creates a new list with the same type)
  final copy2 = List.of(original);

  // 3. List.from (allows casting element types)
  final copy3 = List<num>.from(original);

  // Modifying the copy does not affect the original
  copy1.add(4);
  print(original); // [1, 2, 3]
  print(copy1);    // [1, 2, 3, 4]
}

Sets and Maps

Sets and Maps use the spread operator (...) or their respective .of() constructor:

void main() {
  final originalMap = {'name': 'Alice', 'role': 'Admin'};

  // Shallow copy Map
  final mapCopy = {...originalMap, 'role': 'User'};
  print(originalMap['role']); // Admin
  print(mapCopy['role']);     // User

  final originalSet = {'apple', 'banana'};
  final setCopy = Set.of(originalSet);
  setCopy.add('cherry');
}

The copyWith Idiom for Objects

Because Dart objects do not provide a built-in clone mechanism, the standard Dart and Flutter pattern is to implement a copyWith method. This creates a new immutable instance while selectively replacing certain fields:

class User {
  final String id;
  final String name;
  final String email;

  const User({
    required this.id,
    required this.name,
    required this.email,
  });

  // copyWith allows overriding specific properties
  User copyWith({
    String? id,
    String? name,
    String? email,
  }) {
    return User(
      id: id ?? this.id,
      name: name ?? this.name,
      email: email ?? this.email,
    );
  }

  @override
  String toString() => 'User(id: $id, name: $name, email: $email)';
}

void main() {
  const alice = User(id: 'u-1', name: 'Alice', email: 'alice@example.com');

  // Clone with updated email
  final updatedAlice = alice.copyWith(email: 'new-alice@example.com');

  print(alice);        // User(id: u-1, name: Alice, email: alice@example.com)
  print(updatedAlice); // User(id: u-1, name: Alice, email: new-alice@example.com)
}

Deep Copying

In a deep copy, both the container and all nested objects are recursively duplicated so that no mutable references are shared between the original and the clone.

Deep Copy via JSON Serialization

For data structures composed strictly of JSON-encodable types (Maps, Lists, Strings, Numbers, Booleans), a quick way to achieve deep duplication is round-tripping through JSON:

import 'dart:convert';

void main() {
  final original = [
    {'title': 'Task 1', 'completed': false},
    {'title': 'Task 2', 'completed': true},
  ];

  // Deep clone via jsonEncode / jsonDecode
  final List<dynamic> deepCopy = jsonDecode(jsonEncode(original));

  // Mutating nested data in the copy does not affect the original
  (deepCopy[0] as Map<String, dynamic>)['completed'] = true;

  print(original[0]['completed']); // false
  print(deepCopy[0]['completed']); // true
}

Custom Deep Copy Method

For domain classes with complex behaviors, implementing explicit recursive copy methods is safer, more performant, and fully type-checked:

class OrderItem {
  String product;
  int quantity;

  OrderItem(this.product, this.quantity);

  OrderItem clone() => OrderItem(product, quantity);
}

class Order {
  final String id;
  final List<OrderItem> items;

  Order(this.id, this.items);

  Order deepCopy() {
    return Order(
      id,
      items.map((item) => item.clone()).toList(),
    );
  }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents