Sub topic 1
Immutable Data Classes in Flutter with freezed
Prerequisites
This chapter assumes you know Dart classes, constructors, named parameters, and null safety. You should also know the basics of a Flutter app and how to run commands in a terminal. Familiarity with Dart 3 features, such as sealed classes, helps but is not required.
Why immutable data classes
An immutable object is an object whose fields cannot change after it is created. Flutter rebuilds widgets when state changes. If a shared object can change in place, a widget may show stale data without Flutter noticing. Immutable objects prevent this. To change state, you create a new object and pass it to setState or your state manager.
Value equality and the boilerplate it requires
By default, Dart compares objects by identity. Two objects are equal only if they are the same instance. Value equality instead compares the fields. To get it by hand, you must write ==, hashCode, copyWith, and toString. That is a lot of code to keep in sync. The freezed package generates all four for you.
Installing freezed and running build_runner
freezed is a code generator. It reads your annotated class and writes a second file with the boilerplate. build_runner is the tool that runs generators. Run these commands in your project folder:
dart pub add freezed_annotation json_annotation
dart pub add --dev build_runner freezed json_serializable
dart run build_runner build --delete-conflicting-outputsYour first freezed class
Declaring and using the class
Create lib/person.dart with the following code:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'person.freezed.dart';
@freezed
abstract class Person with _$Person {
const factory Person({
required String name,
@Default(0) int age,
}) = _Person;
}
void main() {
const ada = Person(name: 'Ada', age: 36);
final older = ada.copyWith(age: 37);
print(ada == older); // false
print(older); // Person(name: Ada, age: 37)
}The required keyword makes name mandatory. The @Default(0) annotation gives age a fallback value. The part line tells Dart where the generated code lives. Until you run build_runner, that file does not exist, and the editor will report errors.
Exercise
Why does ada == older print false?
Show answer
copyWith creates a new object with age set to 37. Ada's age is 36, so the fields differ and value equality returns false.