agentleFS
Poorgramer-ZackPoorgramer-Zack/dart-expert-skills/skills/freezed/SKILL.md

generating-freezed-models

Skill7 starsChanged 8 months agoMITView on GitHub

Generates immutable Dart data classes, sealed union types, and deep copyWith using Freezed (v3.2.x) with optional json_serializable integration. Use when creating DTOs, API response models, app state classes, or any model requiring immutability, pattern matching, or JSON serialization. Activates on: @freezed annotation, freezed_annotation import, immutable data class request, copyWith deep nesting, union/sealed types for loading/data/error states, generic response wrappers, or build_runner code generation for models.

The file

We split this skill into the rules it gives an agent

9 rules. About 0 are common, 2 are distinctive, and 7 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 7

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use Freezed union types for sealed state modeling with automatic subtypes.

    line 99
  2. Very specific:

    When a Freezed class contains another Freezed class, deep copyWith chaining is generated automatically.

    line 126
  3. Very specific:

    Default: Always use @freezed (immutable).

    line 134
  4. Very specific:

    Use @JsonKey to customize field serialization:

    line 139
  5. Distinctive:

    Use Freezed for all DTOs and app state classes.

    line 163
  6. Very specific:

    Add a private constructor (const ClassName._()) to enable custom getters/methods.

    line 164
  7. Very specific:

    Use switch expressions instead of .when() / .map().

    line 165
  8. Very specific:

    Default to @freezed (immutable).

    line 166
  9. Very specific:

    Avoid @unfreezed in app state.

    line 170

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Freezed Guide (v3.2.x)

Goal

Generate immutable data classes, union types, and deep copyWith using Freezed v3.2.x. Complements Dart 3 sealed classes by adding copyWith, ==/hashCode, and JSON serialization via json_serializable.

Instructions

1. Dependencies and Environment Setup

Because Freezed relies heavily on code generation, ensure your pubspec.yaml is fully configured:

dependencies:
  freezed_annotation: ^3.2.5
  json_annotation: ^4.11.0 # If mutual conversion with JSON is required

dev_dependencies:
  build_runner: ^2.14.1
  freezed: ^3.2.5
  json_serializable: ^6.13.1 # If mutual conversion with JSON is required

2. Defining an Immutable Data Class

import 'package:freezed_annotation/freezed_annotation.dart';

// You MUST declare part files; the name must exactly match the current file
part 'user_model.freezed.dart';
part 'user_model.g.dart'; // If utilizing JSON serialization

// Freezed 3.x: prefer `sealed` modifier for exhaustive pattern matching
@freezed
sealed class UserModel with _$UserModel {
  const factory UserModel({
    required String id,
    required String name,
    @Default(18) int age,
    @JsonKey(name: 'is_active') @Default(true) bool isActive,
  }) = _UserModel;

  // Required for JSON serialization
  factory UserModel.fromJson(Map<String, Object?> json) => 
      _$UserModelFromJson(json);
}

After every model change, run dart run build_runner build -d.

3. Custom Getters and Methods

To add computed properties or methods, add a private parameterless constructor.

@freezed
abstract class Product with _$Product {
  // private constructor required to add custom methods
  const Product._();
  
  const factory Product({
    required double price,
    required double discountRate,
  }) = _Product;

  // Custom Getter
  double get discountedPrice => price * (1 - discountRate);

  // Custom Method
  bool isFree() => discountedPrice == 0;
}

4. Generic Types Support

@freezed
@JsonSerializable(genericArgumentFactories: true) // required for generic JSON parsing
sealed class PaginatedResponse<T> with _$PaginatedResponse<T> {
  const factory PaginatedResponse({
    required int currentPage,
    required int totalPages,
    required List<T> data,
  }) = _PaginatedResponse<T>;

  // fromJson for generics requires a conversion function parameter
  factory PaginatedResponse.fromJson(
    Map<String, dynamic> json,
    T Function(Object? json) fromJsonT,
  ) => _$PaginatedResponseFromJson(json, fromJsonT);
}

5. Union Types and Dart 3 Pattern Matching

Use Freezed union types for sealed state modeling with automatic subtypes.

@freezed
sealed class ApiResponse with _$ApiResponse {
  const factory ApiResponse.loading() = ApiResponseLoading;
  const factory ApiResponse.data(List<String> items) = ApiResponseData;
  const factory ApiResponse.error(String message) = ApiResponseError;
}

Use Dart 3 native pattern matching with Freezed union types:

Widget buildStatus(ApiResponse response) {
  return switch (response) {
    ApiResponseLoading() => const CircularProgressIndicator(),
    ApiResponseData(:final items) => Text('Item Count: ${items.length}'),
    ApiResponseError(:final message) => Text('Error: $message'),
  };
}

Prefer native switch expressions over .when() / .map() — better compiler exhaustiveness checking.

6. Deep Copy (copyWith) vs @unfreezed

6.1 Automatic Deep CopyWith

When a Freezed class contains another Freezed class, deep copyWith chaining is generated automatically.

// Instead of: user.copyWith(address: user.address.copyWith(city: 'Taipei'))
final newUser = user.copyWith.address(city: 'Taipei');

6.2 When to use @unfreezed

  • Default: Always use @freezed (immutable).
  • @unfreezed allows mutable fields (user.age = 20) but skips ==/hashCode generation.
  • Anti-pattern in Riverpod/BLoC — breaks unidirectional data flow. Only consider for large mutable forms where deep-copying causes measurable performance issues.

7. JSON Serialization with @JsonKey

Use @JsonKey to customize field serialization:

  • Ignore a field: @JsonKey(includeFromJson: false, includeToJson: false)
  • Custom converter for non-standard formats (e.g., date strings):
class MyDateConverter implements JsonConverter<DateTime, String> {
  const MyDateConverter();
  @override
  DateTime fromJson(String json) => DateTime.parse(json.replaceAll('/', '-'));
  @override
  String toJson(DateTime object) => object.toIso8601String();
}

@freezed
sealed class Event with _$Event {
  const factory Event({
    @MyDateConverter() required DateTime eventDate,
  }) = _Event;
  // ... fromJson ...
}

8. Summary

  1. Use Freezed for all DTOs and app state classes.
  2. Add a private constructor (const ClassName._()) to enable custom getters/methods.
  3. Use switch expressions instead of .when() / .map().
  4. Default to @freezed (immutable); avoid @unfreezed in app state.

Constraints

  • Generics with JSON: always add @JsonSerializable(genericArgumentFactories: true).
  • Avoid @unfreezed in app state; use only for mutable form models where deep-copy performance is proven problematic.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.