Sub topic 8
Adding getters and methods
This chapter assumes you can already declare a freezed class and run build_runner, as covered in the earlier chapters. It shows how to put your own getters and methods on a freezed class, why that needs one extra line, and what the generated code does with your members.
Why a plain freezed class cannot have members
A freezed class is declared with a const factory constructor that redirects to a generated class such as _Person. The generated class holds the fields. By default it only implements your abstract class and does not extend it. A getter or method that you write in the abstract class has no concrete implementation in the generated class, so the generated file fails to compile.
The fix is a private, unnamed constructor:
const Temperature._();With this constructor present, freezed generates _Temperature extends Temperature instead. The generated class inherits your members and calls your private constructor. The constructor has no parameters and no body. It exists only as a signal to freezed.
A first example: a computed getter
This is the Temperature class with a derived value. The fields stay in the factory. Everything computed from them goes in the class body.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'temperature.freezed.dart';
@freezed
abstract class Temperature with _$Temperature {
const Temperature._();
const factory Temperature({required double celsius}) = _Temperature;
double get fahrenheit => celsius * 9 / 5 + 32;
bool get isFreezing => celsius <= 0;
Temperature warmedBy(double degrees) =>
copyWith(celsius: celsius + degrees);
}
void main() {
const t = Temperature(celsius: 100);
print(t.fahrenheit); // 212.0
print(t.warmedBy(-100).isFreezing); // true
}Three points about this code:
- Inside the class body you can read
celsiusdirectly. The mixin_$Temperaturedeclares every field as a getter, so the abstract class sees them. copyWithis also provided by the mixin. A method that "changes" the object builds a new one and returns it. Nothing is mutated.- The constructor is
constbecause the factory isconst. If the private constructor is notconst, you lose the ability to create const instances such asconst Temperature(celsius: 100).
What custom members are not part of
Members you add are plain Dart. Freezed does not look at them when it generates the other parts of the class.
| Generated feature | Includes your getters? |
|---|---|
| `==` and `hashCode` | No, only the constructor fields |
| `toString` | No, only the constructor fields |
| `copyWith` | No, you cannot pass a getter as an argument |
| `toJson` | No, only the constructor fields |
This is usually what you want. Derived values such as fahrenheit should not be stored or compared, because they follow from the fields. Two Temperature objects with the same celsius are equal, and fahrenheit agrees for both.
If a value is expensive to compute, remember that a getter runs on every access. Freezed does not cache it. Compute it once into a local variable in the code that uses it, or store it as a real field.
A larger example: a cart with methods
Methods are the right place for update operations that are meaningful in your domain. They give callers a name to use instead of repeating copyWith expressions throughout the widget tree.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'cart.freezed.dart';
@freezed
abstract class CartItem with _$CartItem {
const CartItem._();
const factory CartItem({
required String sku,
required int priceCents,
@Default(1) int quantity,
}) = _CartItem;
int get lineTotalCents => priceCents * quantity;
CartItem withQuantity(int value) {
if (value < 1) {
throw ArgumentError.value(value, 'value', 'must be at least 1');
}
return copyWith(quantity: value);
}
}
@freezed
abstract class Cart with _$Cart {
const Cart._();
const factory Cart({
@Default(<CartItem>[]) List<CartItem> items,
}) = _Cart;
static const empty = Cart();
bool get isEmpty => items.isEmpty;
int get totalCents =>
items.fold(0, (sum, item) => sum + item.lineTotalCents);
Cart add(CartItem item) {
final index = items.indexWhere((i) => i.sku == item.sku);
if (index == -1) {
return copyWith(items: [...items, item]);
}
final existing = items[index];
final merged = existing.withQuantity(existing.quantity + item.quantity);
return copyWith(items: [...items]..[index] = merged);
}
Cart remove(String sku) =>
copyWith(items: items.where((i) => i.sku != sku).toList());
}
void main() {
var cart = Cart.empty;
cart = cart.add(const CartItem(sku: 'tea', priceCents: 450));
cart = cart.add(const CartItem(sku: 'tea', priceCents: 450, quantity: 2));
cart = cart.add(const CartItem(sku: 'mug', priceCents: 1200));
print(cart.totalCents); // 2550
print(cart.remove('mug').totalCents); // 1350
}Some details are worth noting here:
static const empty = Cart();is a static member. Static members belong to the class, so they work with or without the private constructor. Because the default list is a const literal,Cart()can be a compile-time constant.- Validation that depends on logic, such as
withQuantity, belongs in a method. Simple field checks fit better in an@Assert, which you saw in the defaults chapter. addnever editsitems. It builds a new list with the spread operator and passes it tocopyWith. A method that callsitems.add(...)would try to modify the list that freezed has wrapped to be unmodifiable, and it would throw anUnsupportedError. See the pitfalls chapter for the full story on collections.
Overriding toString and other Object members
A member that you declare yourself takes priority over the generated one. Declare toString in the class body and freezed's version in the mixin is no longer used:
@override
String toString() => 'Temperature(${celsius.toStringAsFixed(1)} °C)';The same applies to == and hashCode, but overriding those is rarely a good idea. The point of freezed is that they are generated consistently from the fields. If you override one, override both and keep them consistent.
Overriding toString is the more common case, for example to hide a sensitive field from logs.
Members on unions
A sealed union has several constructors, and each generates its own subclass. The private constructor goes in the base class, and the members you declare there are available on every case.
import 'package:freezed_annotation/freezed_annotation.dart';
part 'load_state.freezed.dart';
@freezed
sealed class LoadState with _$LoadState {
const LoadState._();
const factory LoadState.loading() = LoadStateLoading;
const factory LoadState.data(List<String> items) = LoadStateData;
const factory LoadState.error(String message) = LoadStateError;
bool get isLoading => this is LoadStateLoading;
List<String> get itemsOrEmpty => switch (this) {
LoadStateData(:final items) => items,
_ => const [],
};
}The helper getters keep widget code short. A widget can write if (state.isLoading) instead of repeating a pattern match. When a decision must cover every case, such as choosing which widget to show, use a full switch without a wildcard so the compiler checks exhaustiveness. The _ => branch above is acceptable only because "everything else is empty" is the real rule.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Generated file reports a missing concrete implementation of your getter | No `const Name._();` constructor | Add the private constructor and rerun `build_runner` |
| `const Name(...)` is rejected as not constant | The private constructor lacks `const` | Write `const Name._();` |
| Your getter does not appear in `toString` or JSON | By design | Make it a constructor field if it must be stored |
| Method throws `UnsupportedError` on a list | You mutated a field list in place | Build a new list and call `copyWith` |
Adding or removing const Name._(); changes the shape of the generated code, so rerun dart run build_runner build --delete-conflicting-outputs after either change. An analyzer error that mentions _$Name right after editing the class usually means the generated file is stale.
Choosing between a getter, a method and a field
- Use a getter for a cheap value derived only from the fields and with no arguments, such as
fahrenheitorisEmpty. - Use a method when the operation takes arguments, can fail, or returns a new object, such as
addorwithQuantity. - Use a constructor field when the value must be stored, compared, copied, or serialized.
Exercise
A teammate adds String get displayName => '$first $last'; to a freezed Person class and gets a compile error in person.freezed.dart. Equal objects are also expected to print the display name in toString. What two things do you need to change or know?
Show answer
Add const Person._(); to the class so the generated _Person extends Person and inherits the getter, then rerun dart run build_runner build --delete-conflicting-outputs. The generated toString only includes constructor fields, so displayName will not appear in it. To include it, override toString yourself in the class body.
Exercise
Write a method Cart clear() for the Cart class above, and explain why items.clear() would be wrong.
Show answer
Cart clear() => copyWith(items: const []); (or Cart.empty). items.clear() mutates the list in place. Freezed wraps list fields in an unmodifiable view, so it would throw UnsupportedError. Even if it worked, it would break immutability, because other references to the same cart would see the change.