A state update is easier to review when the old value stays available. An immutable model uses final fields and creates a new instance for changes. This is useful in a Flutter state container, a cache snapshot or an event-processing service.
Worked example
Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.
class CartItem {
const CartItem({required this.sku, required this.quantity});
final String sku;
final int quantity;
CartItem copyWith({int? quantity}) =>
CartItem(sku: sku, quantity: quantity ?? this.quantity);
}
void main() {
const before = CartItem(sku: 'CABLE-1', quantity: 1);
final after = before.copyWith(quantity: 3);
print('Before: ${before.quantity}; after: ${after.quantity}');
print(identical(before, after));
}Follow the data and control flow
The copy keeps the SKU and replaces only the requested quantity. The original object still holds quantity one. Two instances are not identical merely because their values are similar; value equality requires its own definition or a suitable generated implementation.
This copyWith contract uses null to mean “leave unchanged.” That works for a non-nullable quantity but is insufficient when a nullable field must distinguish “keep” from “set to null.” Use an explicit sentinel, wrapper or generated copy contract for that case.
A mistake to avoid
Final fields containing a mutable list are only shallowly immutable. A caller can still mutate that list unless you copy or expose an appropriate immutable view. Validate a quantity before accepting an update instead of relying on the copy operation to make arbitrary input meaningful.
Practice and verification
Add a validated quantity rule and test that a failed update leaves the original intact. Extend the model with tags and demonstrate the difference between copying the tag list and sharing it. Continue with value equality before using models in sets.