Lesson 0002 • Freezed & Domain Models

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:

TypeScript interface + object spread in a React codebase
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:

  1. 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, and JSON.parse() returns an untyped Map<String, dynamic>, not a Part.
  2. Dart == defaults to reference identity (like JS ===): Two separate Part(id: 'p1', name: '10k') instances are not == unless the class overrides operator == and hashCode.

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)"]
Figure 2.1: How build_runner reads @freezed annotations in catalog_models.dart and emits part files.

Block 1: Updating pubspec.yaml

We add two lightweight annotation packages to dependencies: and three code generators to dev_dependencies::

Updated dependencies in tutorial/apps/0002-immutable-domain-models-with-freezed/pubspec.yaml
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.2

2. Building lib/catalog/catalog_models.dart Block by Block

Block 1: part Directives and the Container Model

Part directives and @freezed Container class in lib/catalog/catalog_models.dart
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:

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 Part class with @Default values and computed 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;
}

Block 3: CatalogSnapshot & 1-to-1 (Container, Slot) Lookup

Finally, we model CatalogSnapshot—the versioned root state object—and its findOccupyingSlotPart domain method:

@freezed CatalogSnapshot class with empty factory, exportFileName, and findOccupyingSlotPart
@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;
  }
}

Complete lib/catalog/catalog_models.dart Listing

tutorial/apps/0002-immutable-domain-models-with-freezed/lib/catalog/catalog_models.dart
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.

tutorial/apps/0002-immutable-domain-models-with-freezed/test/catalog_models_test.dart
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

Interactive Lab: Authoring a @freezed Model with Null Safety

Skill Practice • Tight Feedback Loop

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."

:::

Retrieval Practice: Freezed, Part Files & Null Safety

3 Questions • Equal-Length Options
1. Why do we use @freezed classes in Dart instead of plain classes like TypeScript interfaces?
2. Why must Part and CatalogSnapshot declare a private const Part._() constructor inside their class bodies?
3. How does CatalogSnapshot.findOccupyingSlotPart enforce the 1-to-1 (Container, Slot) workbench storage rule?

Verification Lab: Generate Freezed Part Files & Run Model Tests

CLI Gate • Zero Warnings & 100% Green

Run static analysis and the unit + widget test suite inside tutorial/apps/0002-immutable-domain-models-with-freezed:

Terminal verification commands for Lesson 0002
cd tutorial/apps/0002-immutable-domain-models-with-freezed
flutter analyze
flutter test

Expected terminal output:

Verified output of flutter analyze && flutter test
Analyzing 0002-immutable-domain-models-with-freezed...
No issues found!
00:01 +3: All tests passed!