Sub topic 6
Changing data with copyWith
An immutable object cannot be edited in place, so every change produces a new object. In freezed, the generated copyWith method does this. This chapter covers how copyWith behaves, how it handles nullable fields and collections, and where it can surprise you.
This chapter assumes you have finished the setup chapters. That means you have a working build_runner configuration and can declare a freezed class with required, default and nullable fields. It also assumes you know Dart named parameters and null safety.
What copyWith does
copyWith takes the same fields as the constructor, all optional. It returns a new instance. Fields you pass get the new values, and every other field is copied from the original.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'person.freezed.dart';
@freezed
abstract class Person with _$Person {
@Assert('age >= 0')
const factory Person({
required String name,
@Default(0) int age,
String? nickname,
}) = _Person;
}
void main() {
const ada = Person(name: 'Ada', age: 36);
final older = ada.copyWith(age: 37);
print(ada.age); // 36, the original is untouched
print(older.age); // 37
print(ada == older); // false
}The original ada never changes. Any code that still holds a reference to it sees the same values it saw before. That is the property that makes state predictable in Flutter. A widget that received ada cannot have its data altered by code elsewhere.
Why not write it by hand
A hand-written copyWith usually looks like this:
class Profile {
const Profile({required this.name, this.nickname});
final String name;
final String? nickname;
Profile copyWith({String? name, String? nickname}) =>
Profile(name: name ?? this.name, nickname: nickname ?? this.nickname);
}This version has a flaw. copyWith(nickname: null) is indistinguishable from not passing the argument, so nickname ?? this.nickname keeps the old value. You can never clear a nullable field. Every added field also means editing the parameter list, the constructor call and the equality code.
Freezed avoids the flaw. Its generated method tells "argument omitted" apart from "argument is null", using an internal sentinel value for omitted arguments.
void clearNickname() {
const grace = Person(name: 'Grace', nickname: 'Amazing');
final cleared = grace.copyWith(nickname: null);
final unchanged = grace.copyWith(age: 40);
print(cleared.nickname); // null
print(unchanged.nickname); // Amazing
}For a non-nullable field such as name, passing null is a compile-time error, so you cannot corrupt a required field by accident.
Assertions run on every copy
copyWith calls the real constructor, so validation still applies. With @Assert('age >= 0') on Person:
void invalidCopy() {
const ada = Person(name: 'Ada', age: 36);
ada.copyWith(age: -1); // AssertionError in debug mode
}Dart asserts are active only in debug and test runs. In a release build, age: -1 passes silently. If a rule must hold in production, validate before you construct the object, or throw an explicit exception from a factory or method.
Updating collections
copyWith replaces fields. It does not look inside them. For a list field, you build a new list and pass it in.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'cart.freezed.dart';
@freezed
abstract class Cart with _$Cart {
const factory Cart({
@Default([]) List<String> items,
}) = _Cart;
}
Cart addItem(Cart cart, String item) =>
cart.copyWith(items: [...cart.items, item]);
Cart removeItem(Cart cart, String item) =>
cart.copyWith(items: cart.items.where((i) => i != item).toList());The spread operator [...cart.items, item] creates a new list. This is the central rule for collections: never mutate the list, always replace it.
The shallow immutability trap
A freezed class is immutable at the level of its fields: you cannot reassign cart.items. The list object that field points to may still be mutable. Calling cart.items.add('x') can change the list that both the old and new Cart objects share, and nothing in copyWith stops it.
Freezed can wrap collection fields so they throw on mutation. The makeCollectionsUnmodifiable option controls this, and its default has differed between versions. Check the documentation for the version you have installed. Even if your version wraps collections, treat the rule above as the habit to keep. It protects you when a model holds a type freezed cannot wrap, such as a custom class with mutable fields.
Nested updates
Updating a field two levels deep by hand means nesting two copyWith calls. When the inner field is also a freezed class, freezed generates a shortcut.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user.freezed.dart';
@freezed
abstract class Address with _$Address {
const factory Address({required String city, String? street}) = _Address;
}
@freezed
abstract class User with _$User {
const factory User({
required String name,
required Address address,
}) = _User;
}
User moveVerbose(User user) =>
user.copyWith(address: user.address.copyWith(city: 'Oslo'));
User move(User user) => user.copyWith.address(city: 'Oslo');Both functions return the same result. user.copyWith.address(...) takes the fields of Address, builds the new address, and puts it into a new User. It only exists for fields whose type is a freezed class. It does not reach into lists or maps, so changing one element of a List<Address> still needs manual list rebuilding.
copyWith on union cases
With a sealed union, each case is its own class with its own copyWith. Using the LoadState union from the previous chapter:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'load_state.freezed.dart';
@freezed
sealed class LoadState with _$LoadState {
const factory LoadState.loading() = LoadStateLoading;
const factory LoadState.data(List<String> items) = LoadStateData;
const factory LoadState.error(String message) = LoadStateError;
}
LoadState appendItem(LoadState state, String item) => switch (state) {
LoadStateData(:final items) =>
state.copyWith(items: [...items, item]),
_ => state,
};Inside the first branch, Dart has narrowed state to LoadStateData, so copyWith(items: ...) is available. On the base type LoadState, copyWith exists only for fields shared by every case. Here no field is shared, so you cannot call it without matching first. copyWith also never turns one case into another. To go from loading to data, construct a new LoadState.data(...).
Using copyWith in Flutter state
A common pattern is a notifier that holds an immutable value and replaces it on every change:
import 'package:flutter/foundation.dart';
class PersonNotifier extends ValueNotifier<Person> {
PersonNotifier(super.value);
void birthday() => value = value.copyWith(age: value.age + 1);
void rename(String name) => value = value.copyWith(name: name);
}ValueNotifier notifies listeners when the new value is not equal to the old one. Freezed's value equality makes that check correct. copyWith(age: 37) produces an unequal object, so listeners fire. A copy with identical values is equal, so no rebuild happens.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Calling `copyWith` and discarding the result | The original is unchanged, so nothing seems to happen | Assign the result: `state = state.copyWith(...)` |
| Calling `list.add` on a field | Shared list changes, with no new object | Pass `[...list, item]` to `copyWith` |
| Expecting `copyWith(x: null)` to work on a required field | Compile error | Make the field nullable (`String?`) |
| Relying on `@Assert` in release builds | Invalid data passes silently | Validate explicitly where it matters |
| Editing `.freezed.dart` by hand | Changes are lost on the next build | Change the source class and rerun `build_runner` |
Exercises
Exercise
A hand-written copyWith uses nickname: nickname ?? this.nickname. Why can't it clear the nickname, and how does the freezed version avoid that?
Show answer
Passing null is the same as omitting the argument, so the ?? expression falls back to the old value. Freezed's generated copyWith uses an internal sentinel for "not provided", so an explicit null is treated as a real value and stored.
Exercise
Given const Cart({@Default([]) List<String> items}), write a function Cart clear(Cart c) that returns a cart with no items, and explain why c.items.clear() would be the wrong approach.
Show answer
Cart clear(Cart c) => c.copyWith(items: []);. Calling c.items.clear() mutates the list in place, which is shallow immutability being bypassed. The object identity doesn't change, so code comparing old and new states may not detect a change, and other holders of the old Cart see it emptied.
Exercise
Using the User and Address classes above, write a function that sets the street to 'Main St' without changing the city, using the nested copyWith shortcut.
Show answer
User setStreet(User u) => u.copyWith.address(street: 'Main St');. Omitted fields (here city) are copied from the existing address.