Immutable Domain Models with Freezed & JSON Serialization
Replace TypeScript interfaces, object spread ({ ...part }), and JSON.parse with Dart 3 sound null safety, @freezed data classes, copyWith, and build_runner codegen.
Why Plain Dart Classes Aren't Like TypeScript Interfaces
In TypeScript, modeling an immutable domain entity takes zero runtime code:
export interface Part {
readonly id: string;
readonly name: string;
readonly quantity: number;
readonly containerId?: string | null;
readonly slot?: string | null;
}
// Cloning with an updated field uses JS object spread:
const updated: Part = { ...part, quantity: part.quantity + 10 };When you move to Dart, two language differences immediately stand out:
- Dart is nominally typed and compiles to native machine code: Classes are real runtime types, not erased compile-time shapes. You cannot write
{ ...part, quantity: 10 }on a class instance, andJSON.parse()returns an untypedMap<String, dynamic>, not aPart. - Dart
==defaults to reference identity (like JS===): Two separatePart(id: 'p1', name: '10k')instances are not==unless the class overridesoperator ==andhashCode.
Rather than hand-writing hundreds of lines of boilerplate copyWith, operator ==, hashCode, toString(), and fromJson/toJson methods, production Flutter apps use freezed + json_serializable.Both freezed and riverpod were created by Remi Rousselet and are designed to work together: because @freezed generates deep structural value equality (==), Riverpod providers and tests can compare snapshots and parts by value out of the box.
In this lesson, you will build lib/catalog/catalog_models.dart in ./tutorial/apps/0002-immutable-domain-models-with-freezed/ with our three core domain models: Container, Part, and CatalogSnapshot.
1. Adding Freezed & JSON Codegen to pubspec.yaml
flowchart LR Src["lib/catalog/catalog_models.dart<br/>(@freezed classes)"] --> Runner["dart run build_runner build"] Runner --> FreezedPart["catalog_models.freezed.dart<br/>(copyWith, ==, hashCode, toString)"] Runner --> JsonPart["catalog_models.g.dart<br/>(_$PartFromJson / _$PartToJson)"]
Block 1: Updating pubspec.yaml
We add two lightweight annotation packages to dependencies: and three code generators to dev_dependencies::
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.8
flutter_riverpod: ^3.4.3
freezed_annotation: ^3.1.0
json_annotation: ^4.12.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^6.0.0
build_runner: ^2.16.2
freezed: ^4.0.3
json_serializable: ^6.15.2freezed_annotation&json_annotation: Tiny runtime packages containing the@freezedand@Default(...)annotations.build_runner,freezed, &json_serializable: Compile-time code generators (only indev_dependencies) that inspect your AST and write.freezed.dartand.g.dartcompanion files.
2. Building lib/catalog/catalog_models.dart Block by Block
Block 1: part Directives and the Container Model
import 'package:freezed_annotation/freezed_annotation.dart';
part 'catalog_models.freezed.dart';
part 'catalog_models.g.dart';
@freezed
abstract class Container with _$Container {
const Container._();
const factory Container({
required String id,
required String name,
String? description,
}) = _Container;
factory Container.fromJson(Map<String, dynamic> json) =>
_$ContainerFromJson(json);
}Every line in this block teaches a core Dart 3 and Freezed idiom:
part 'catalog_models.freezed.dart';andpart 'catalog_models.g.dart';:- In Dart, a Part File (
part/part of) splits a single library across multiple physical files so generated code can share the exact same private scope (identifiers starting with_).
- In Dart, a Part File (
abstract class Container with _$Container:- The
withkeyword applies a Dart mixin (_$Container, generated insidecatalog_models.freezed.dart) that injects the field getters (id,name,description),copyWith,toJson(),operator ==, andhashCode.
- The
const Container._();:- A private, empty
constconstructor (ClassName._()). Whenever a Freezed class defines custom methods or getters, Freezed's generated_Containerimplementation class extendsContainer, which requiresContainerto have a generative constructor (const Container._()) for the subclass to callsuper._().
- A private, empty
const factory Container({ required String id, required String name, String? description }) = _Container;:- A redirecting factory constructor that delegates construction to the generated
_Containerclass. - Notice Dart's sound null safety:
String idandString nameare guaranteed non-null (required), whileString? descriptionis explicitly nullable and defaults tonullwhen omitted.
- A redirecting factory constructor that delegates construction to the generated
factory Container.fromJson(Map<String, dynamic> json) => _$ContainerFromJson(json);:- Wires
json_serializableso callingContainer.fromJson(map)validates and constructs aContainer, and callingcontainer.toJson()serializes it back to aMap<String, dynamic>.
- Wires
Block 2: The Part Model (@Default & Computed Getters)
Next, we model a workbench Part (10kΩ 0603 1% Resistor, NE555P, etc.) with its electrical Specs and computed stock/location getters:
@freezed
abstract class Part with _$Part {
const Part._();
const factory Part({
required String id,
required String name,
@Default(0) int quantity,
String? lcscCode,
String? mpn,
String? manufacturer,
String? category,
String? package,
String? datasheetUrl,
String? containerId,
String? slot,
int? lowStockThreshold,
String? notes,
@Default(<String, String>{}) Map<String, String> specs,
}) = _Part;
factory Part.fromJson(Map<String, dynamic> json) => _$PartFromJson(json);
bool get isLowStock => quantity <= (lowStockThreshold ?? 0);
bool get isUnassigned => containerId == null;
}@Default(0) int quantity: Tells both the Dart constructor andfromJsondeserializer to defaultquantityto0if omitted—soquantityis always a non-nullableint!@Default(<String, String>{}) Map<String, String> specs: Stores the ordered key-value Specs ('Capacitance': '100nF','Voltage Rated': '50V'). Notice that aconstmap literal in Dart is written<KeyType, ValueType>{}.bool get isLowStock => quantity <= (lowStockThreshold ?? 0);:- In Dart,
Type get propName => ...defines a computed getter (just likeget isLowStock(): booleanin a TypeScript class). - If
lowStockThresholdisnull,lowStockThreshold ?? 0evaluates to0, meaning a part with no custom threshold is still flagged as low stock when its quantity hits0.
- In Dart,
copyWithcan set nullable fields back tonull! Unlike hand-writtencopyWith({String? slot}) => Part(slot: slot ?? this.slot)methods (which cannot distinguish an omitted argument fromslot: null), Freezed's generatedpart.copyWith(containerId: null, slot: null)cleanly resets nullable fields tonull.
Block 3: CatalogSnapshot & 1-to-1 (Container, Slot) Lookup
Finally, we model CatalogSnapshot—the versioned root state object—and its findOccupyingSlotPart domain method:
@freezed
abstract class CatalogSnapshot with _$CatalogSnapshot {
const CatalogSnapshot._();
const factory CatalogSnapshot({
@Default(1) int schemaVersion,
required DateTime updatedAt,
@Default(<Container>[]) List<Container> containers,
@Default(<Part>[]) List<Part> parts,
}) = _CatalogSnapshot;
factory CatalogSnapshot.fromJson(Map<String, dynamic> json) =>
_$CatalogSnapshotFromJson(json);
factory CatalogSnapshot.empty({DateTime? now}) => CatalogSnapshot(
schemaVersion: 1,
updatedAt: (now ?? DateTime.now()).toUtc(),
containers: const [],
parts: const [],
);
String get exportFileName {
final dateStr = updatedAt.toUtc().toIso8601String().split('T').first;
return 'parts-catalog-$dateStr.json';
}
Part? findOccupyingSlotPart(
String? containerId,
String? slot, {
String? excludingPartId,
}) {
final cleanContainerId = containerId?.trim();
final cleanSlot = slot?.trim();
if (cleanContainerId == null ||
cleanContainerId.isEmpty ||
cleanSlot == null ||
cleanSlot.isEmpty) {
return null;
}
final slotLower = cleanSlot.toLowerCase();
for (final existing in parts) {
if (existing.id == excludingPartId) continue;
if (existing.containerId == cleanContainerId &&
existing.slot != null &&
existing.slot!.toLowerCase() == slotLower) {
return existing;
}
}
return null;
}
}factory CatalogSnapshot.empty({DateTime? now}): Creates an emptyschemaVersion: 1catalog with a UTC timestamp (allowing tests to pass a deterministicnowif needed).exportFileName: FormatsupdatedAtintoparts-catalog-YYYY-MM-DD.jsonusing Dart's$variablestring interpolation (equivalent to TypeScript`parts-catalog-${dateStr}.json`).findOccupyingSlotPart(String? containerId, String? slot, {String? excludingPartId}):- Notice the mixed parameter list:
containerIdandslotare positional, while{String? excludingPartId}is an optional named parameter! - Enforces our Glossary domain rule: a Slot inside a Container holds at most one Part (compared case-insensitively after trimming), while bulk parts with
slot == null(or unassigned parts withcontainerId == null) never collide. When editing an existing part, passingexcludingPartId: part.idprevents the part from colliding with itself.
- Notice the mixed parameter list:
Complete lib/catalog/catalog_models.dart Listing
import 'package:freezed_annotation/freezed_annotation.dart';
part 'catalog_models.freezed.dart';
part 'catalog_models.g.dart';
@freezed
abstract class Container with _$Container {
const Container._();
const factory Container({
required String id,
required String name,
String? description,
}) = _Container;
factory Container.fromJson(Map<String, dynamic> json) =>
_$ContainerFromJson(json);
}
@freezed
abstract class Part with _$Part {
const Part._();
const factory Part({
required String id,
required String name,
@Default(0) int quantity,
String? lcscCode,
String? mpn,
String? manufacturer,
String? category,
String? package,
String? datasheetUrl,
String? containerId,
String? slot,
int? lowStockThreshold,
String? notes,
@Default(<String, String>{}) Map<String, String> specs,
}) = _Part;
factory Part.fromJson(Map<String, dynamic> json) => _$PartFromJson(json);
bool get isLowStock => quantity <= (lowStockThreshold ?? 0);
bool get isUnassigned => containerId == null;
}
@freezed
abstract class CatalogSnapshot with _$CatalogSnapshot {
const CatalogSnapshot._();
const factory CatalogSnapshot({
@Default(1) int schemaVersion,
required DateTime updatedAt,
@Default(<Container>[]) List<Container> containers,
@Default(<Part>[]) List<Part> parts,
}) = _CatalogSnapshot;
factory CatalogSnapshot.fromJson(Map<String, dynamic> json) =>
_$CatalogSnapshotFromJson(json);
factory CatalogSnapshot.empty({DateTime? now}) => CatalogSnapshot(
schemaVersion: 1,
updatedAt: (now ?? DateTime.now()).toUtc(),
containers: const [],
parts: const [],
);
String get exportFileName {
final dateStr = updatedAt.toUtc().toIso8601String().split('T').first;
return 'parts-catalog-$dateStr.json';
}
Part? findOccupyingSlotPart(
String? containerId,
String? slot, {
String? excludingPartId,
}) {
final cleanContainerId = containerId?.trim();
final cleanSlot = slot?.trim();
if (cleanContainerId == null ||
cleanContainerId.isEmpty ||
cleanSlot == null ||
cleanSlot.isEmpty) {
return null;
}
final slotLower = cleanSlot.toLowerCase();
for (final existing in parts) {
if (existing.id == excludingPartId) continue;
if (existing.containerId == cleanContainerId &&
existing.slot != null &&
existing.slot!.toLowerCase() == slotLower) {
return existing;
}
}
return null;
}
}3. Unit Testing the Domain Models (test/catalog_models_test.dart)
Unlike widget tests (testWidgets), pure Dart domain logic is tested with test('...', () { ... })—identical to Vitest/Jest unit tests.
import 'package:flutter_test/flutter_test.dart';
import 'package:parts_tracker_skilled/catalog/catalog_models.dart';
void main() {
group('Catalog Freezed Domain Models', () {
test('Part supports value equality, copyWith (including setting nullable fields to null), isLowStock, and JSON round-trip', () {
const resistor = Part(
id: 'p-r10k',
name: '10kΩ 0603 1% Resistor',
quantity: 8,
lowStockThreshold: 10,
containerId: 'c-binder-1',
slot: 'Page 1',
specs: {'Resistance': '10kΩ', 'Tolerance': '±1%'},
);
expect(resistor.isLowStock, isTrue);
expect(resistor.isUnassigned, isFalse);
final restocked = resistor.copyWith(quantity: 50);
expect(restocked.isLowStock, isFalse);
expect(restocked.name, '10kΩ 0603 1% Resistor');
final unassigned = restocked.copyWith(containerId: null, slot: null);
expect(unassigned.isUnassigned, isTrue);
expect(unassigned.slot, isNull);
final roundTripped = Part.fromJson(resistor.toJson());
expect(roundTripped, equals(resistor));
});
test('CatalogSnapshot computes exportFileName and detects case-insensitive (Container, Slot) collisions', () {
final snapshot = CatalogSnapshot(
updatedAt: DateTime.utc(2026, 11, 3, 14, 30),
containers: const [
Container(id: 'c-1', name: 'SMD Binder #1'),
],
parts: const [
Part(
id: 'p-1',
name: '100nF 0603 Cap',
containerId: 'c-1',
slot: 'Page 4',
),
],
);
expect(snapshot.exportFileName, 'parts-catalog-2026-11-03.json');
expect(
snapshot.findOccupyingSlotPart('c-1', ' page 4 ')?.id,
'p-1',
);
expect(
snapshot.findOccupyingSlotPart('c-1', 'page 4', excludingPartId: 'p-1'),
isNull,
);
expect(snapshot.findOccupyingSlotPart('c-1', null), isNull);
});
});
}4. Interactive Practice & Verification
Complete the missing Freezed and Dart 3 tokens for Part below:
part 'catalog_models.freezed.dart';
part 'catalog_models.g.dart';
@freezed
abstract class Part _$Part {
const Part.();
const factory Part({
required String id,
required String name,
@ int quantity,
String? containerId,
int? lowStockThreshold,
}) = _Part;
bool get isLowStock => quantity <= (lowStockThreshold 0);
}:::prompts hint: "Mixins use the 'with' keyword, private named constructors use '._()', Freezed default values use '@Default(0)', and null-coalescing uses '??'." success: "Excellent! You can now read and author @freezed data classes with custom computed getters and sound null safety."
:::
@freezed classes in Dart instead of plain classes like TypeScript interfaces?Part and CatalogSnapshot declare a private const Part._() constructor inside their class bodies?CatalogSnapshot.findOccupyingSlotPart enforce the 1-to-1 (Container, Slot) workbench storage rule?Run static analysis and the unit + widget test suite inside tutorial/apps/0002-immutable-domain-models-with-freezed:
cd tutorial/apps/0002-immutable-domain-models-with-freezed
flutter analyze
flutter testExpected terminal output:
Analyzing 0002-immutable-domain-models-with-freezed...
No issues found!
00:01 +3: All tests passed!