Sub topic 2
What freezed generates for you
This chapter assumes you know Dart classes, named parameters, and null safety, and that you have already run build_runner as set up in the previous chapter. You should also know that part directives link a file to its generated companion.
Generated members
When you annotate a class with @freezed, the generator writes the equality, hash code, string, and copy methods for you. Here is a minimal model:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'person.freezed.dart';
@freezed
abstract class Person with _$Person {
const factory Person({required String name, required int age}) = _Person;
}The generated file provides ==, hashCode, toString(), and copyWith. Two Person objects with the same fields compare equal.
Changing data with copyWith
Freezed objects are immutable, so you never edit a field in place. copyWith returns a new object with selected fields replaced:
void main() {
const ada = Person(name: 'Ada', age: 36);
final older = ada.copyWith(age: 37);
print(ada.age); // 36
print(older.age); // 37
}Defaults, optional fields and assertions
Use @Default to give a field a fallback value, and a nullable type for a field that may be absent. @Assert rejects invalid values when the object is built:
@freezed
abstract class Person with _$Person {
@Assert('age >= 0')
const factory Person({
required String name,
@Default(0) int age,
String? nickname,
}) = _Person;
}Adding getters and methods
A private const constructor lets you add your own members to a freezed class:
@freezed
abstract class Temperature with _$Temperature {
const Temperature._();
const factory Temperature({required double celsius}) = _Temperature;
double get fahrenheit => celsius * 9 / 5 + 32;
}JSON with fromJson and toJson
Add json_serializable as a dependency, a part 'person.g.dart'; directive, and a fromJson factory. Then @JsonKey can rename a field in the JSON output:
part 'person.g.dart';
@freezed
abstract class Person with _$Person {
const factory Person({
required String name,
@JsonKey(name: 'e_mail') String? email,
}) = _Person;
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
}Exercise
Exercise
Given the Person class with @JsonKey(name: 'e_mail') String? email, what key appears in the JSON produced by toJson(), and what happens to a field named email in the JSON input when calling fromJson?
Show answer
The output key is e_mail. fromJson reads the e_mail key, so an input with only email leaves the field null.