Sub topic 13
Updating nested objects
This chapter covers how to change a value deep inside a tree of freezed objects without rebuilding every layer by hand. It assumes you can already declare a freezed class, run build_runner, and use the generated copyWith. You should also know basic Dart null safety and named parameters.
The problem with nested immutable data
Immutable objects cannot be changed in place. To "change" a field, you build a new object that copies every other field. For a flat class, copyWith does this in one call. Real models are rarely flat. A User holds an Address, which may hold a Country, and so on.
Without help, updating the city of a user's address means copying each layer yourself:
User move(User user) => user.copyWith(
address: user.address.copyWith(city: 'Oslo'),
);This works, but each extra level of nesting adds another copyWith call and another place to make a mistake. At three or four levels the code becomes hard to read.
The nested copyWith that freezed generates
When a field's type is itself a freezed class, freezed generates a second, chained form of copyWith for that field. You reach it with copyWith.fieldName.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'user.freezed.dart';
@freezed
abstract class Address with _$Address {
const factory Address({required String city}) = _Address;
}
@freezed
abstract class User with _$User {
const factory User({
required String name,
required Address address,
}) = _User;
}
User move(User user) => user.copyWith.address(city: 'Oslo');The call user.copyWith.address(city: 'Oslo') does three things:
- It reads the current
addressfromuser. - It calls
copyWith(city: 'Oslo')on that address. - It calls
copyWith(address: newAddress)onuserand returns the result.
The original user and its original address are untouched. Fields you did not name, such as user.name, are carried over unchanged.
Going more than one level deep
The chained form continues for as many freezed levels as you have. Suppose an address holds a Country:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'profile.freezed.dart';
@freezed
abstract class Country with _$Country {
const factory Country({required String code}) = _Country;
}
@freezed
abstract class Address with _$Address {
const factory Address({
required String city,
required Country country,
}) = _Address;
}
@freezed
abstract class Profile with _$Profile {
const factory Profile({
required String name,
required Address address,
}) = _Profile;
}
Profile relocate(Profile profile) =>
profile.copyWith.address.country(code: 'NO');Here profile.copyWith.address.country(code: 'NO') replaces only the country code. You can also update a middle level with profile.copyWith.address(city: 'Oslo'). Each step of the chain returns a new object for that level, and freezed wraps it back into its parent.
When nested copyWith is not generated
The chained form depends on the field's type. It exists only when freezed can see that the field is a freezed class (or another type with a suitable copyWith) when it generates code. Several cases do not produce it:
| Field type | Nested copyWith? | What to do instead |
|---|---|---|
| A freezed class | Yes | Use `copyWith.field(...)` |
| A plain Dart class with no `copyWith` | No | Call `copyWith(field: Plain(...))` with a whole new object |
| `List`, `Map`, `Set` | No | Build a new collection and pass it to `copyWith` |
| A nullable freezed class (`Address?`) | Yes, but null-aware | See the next section |
| A `dynamic` or `Object` field | No | Pass a whole replacement value |
Other cases, such as a freezed class that is not yet generated, also fail. If the generator has not run, or the nested type's .freezed.dart file is stale, copyWith.address will not compile. Re-run dart run build_runner build --delete-conflicting-outputs and check again.
Nullable nested objects
When the nested field is nullable, the nested copyWith has to cope with a missing value. In current freezed versions, copyWith.address on a nullable field returns null-safe behavior: it is exposed as a nullable accessor, so you call it with ?.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'contact.freezed.dart';
@freezed
abstract class Address with _$Address {
const factory Address({required String city}) = _Address;
}
@freezed
abstract class Contact with _$Contact {
const factory Contact({
required String name,
Address? address,
}) = _Contact;
}
Contact rename(Contact contact) =>
contact.copyWith.address?.call(city: 'Oslo') ?? contact;Reading this expression: if contact.address is null, there is nothing to update, so contact.copyWith.address is null and the ?? returns the original contact. If the address exists, its city is replaced. This is a deliberate design choice. Updating a field of an object that does not exist has no sensible result, so freezed does not invent one.
If you want to create the address when it is missing, use the regular copyWith and supply a whole object:
Contact setCity(Contact contact, String city) => contact.copyWith(
address: (contact.address ?? const Address(city: '')).copyWith(city: city),
);Be aware that the exact shape of the generated nullable accessor can differ between freezed releases. If the code above does not compile in your version, fall back to the explicit form, which works in every version.
Replacing a field with null
A common surprise concerns setting a nullable field back to null. With freezed, the generated copyWith distinguishes "argument not given" from "argument given as null". So this clears the value:
Contact clearAddress(Contact contact) => contact.copyWith(address: null);Omitting the argument keeps the existing value. Passing null explicitly sets the field to null. This behavior is useful, but it does not carry over to hand-written copyWith methods that use address ?? this.address. Those cannot clear a field, which is one reason to prefer the generated version.
Collections inside nested objects
Collections are the most common place where nested updates go wrong. freezed makes the class immutable, and generated copyWith replaces the whole list. It does not look inside the list.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'cart.freezed.dart';
@freezed
abstract class Item with _$Item {
const factory Item({required String sku, required int qty}) = _Item;
}
@freezed
abstract class Cart with _$Cart {
const factory Cart({required List<Item> items}) = _Cart;
}
Cart addQuantity(Cart cart, String sku) => cart.copyWith(
items: [
for (final item in cart.items)
if (item.sku == sku) item.copyWith(qty: item.qty + 1) else item,
],
);This builds a new list. Items that do not match are reused as they are. The matching item is replaced by a copy with a new quantity. Because Item is immutable, sharing the unchanged items between the old and new cart is safe.
Why nested updates matter for Flutter state
State management tools such as ValueNotifier, Riverpod, and Bloc decide whether to notify listeners by comparing the old and new state. With value equality, two states compare equal only when all their fields, including nested ones, are equal. A nested copyWith produces a state that differs from the old one exactly where you changed it. Widgets watching that state rebuild when something really changed and stay quiet when it did not.
Calling copyWith.address(city: 'Bergen') on a user already in Bergen produces an object equal to the original. A listener that compares states can skip the rebuild.
Testing nested updates
Because equality is generated, you can assert on a whole tree in one expression and check that the original is untouched.
import 'package:test/test.dart';
void main() {
test('nested copyWith changes only the targeted field', () {
const user = User(name: 'Ada', address: Address(city: 'Bergen'));
final moved = user.copyWith.address(city: 'Oslo');
expect(moved, const User(name: 'Ada', address: Address(city: 'Oslo')));
expect(user.address.city, 'Bergen');
expect(moved.name, same(user.name));
});
}The final assertion checks that unchanged fields are reused rather than rebuilt.
Common mistakes
- Forgetting to re-run the generator after changing the nested class. The outer class's nested
copyWithdepends on the inner class's generated code. - Expecting
copyWith.itemsto edit a list element. It does not exist for collections. - Using a plain class for the inner type and then wondering why
copyWith.addressis missing. Make the inner type freezed, or call the regularcopyWithwith a whole object. - Mixing up
copyWith(address: null)and omitting the argument. Only the first clears the field.
Exercise
A Cart is a freezed class with a List<Item> items, and Item is a freezed class with sku and qty. A teammate writes cart.copyWith.items(qty: 2) to change one item's quantity. Why does this fail, and how would you write it correctly?
Show answer
The nested copyWith.field form is generated only for fields whose type is a single freezed class. items is a List, so no copyWith.items exists. Build a new list instead: cart.copyWith(items: [for (final i in cart.items) if (i.sku == sku) i.copyWith(qty: 2) else i]). Unchanged items are reused and only the matching one is copied.
Exercise
Given Profile(name, address: Address(city, country: Country(code))), all freezed, write one expression that changes only the country code to 'SE' without writing nested copyWith calls by hand.
Show answer
profile.copyWith.address.country(code: 'SE'). Each level of the chain returns an updated copy and freezed wraps it into its parent, so name and city are carried over.