本文へ移動
cccskills
無料GitHub で公開

generating-freezed-models

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.

インストール方法を見る

含まれるファイル(1)

  • SKILL.md5.8 KB

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.

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Declarative animation patterns using flutter_animate v4.5.x with composable effects (fade, scale, slide, shimmer, shake, blur), GLSL fragment shaders, and scroll-synchronized animations. Use this skill for adding UI animations and transitions, building staggered or sequenced effects, creating custom animation effects, fixing animation jank or performance issues, implementing shimmer loading states, or adding scroll-driven animations. Supports delays, curves, adaptive effects, and easy extension method chaining (.animate()).

日本語の概要は準備中です。原文の説明を表示しています。

Poorgramer-Zack/dart-expert-skills72026年8月11日 更新

Dart 3 modern features (through 3.10) and Effective Dart best practices including records, patterns, sealed classes, dot shorthands, null-aware collection elements, and wildcard variables. Use when adopting Dart 3.7+ syntax, using dot shorthands for enums or static members, using null-aware elements in lists or maps, using wildcard _ parameters, improving code quality, or reviewing Dart code conventions.

日本語の概要は準備中です。原文の説明を表示しています。

Poorgramer-Zack/dart-expert-skills72026年8月11日 更新

Expert-level guidance for Flutter production applications: architecture decisions (Clean/Layered/Hexagonal/Feature-First), advanced state management (BLoC/Riverpod/GetX), performance optimization (eliminating jank, memory profiling, reducing rebuild overhead), code review with design pattern enforcement, scalability assessments, native platform integration (MethodChannel/EventChannel/FFI), complex UI challenges (custom render objects, slivers), testing strategies (unit/widget/integration/golden), CI/CD pipeline architecture, build optimization, and accessibility compliance. Triggers: 'architecture decision', 'design pattern', 'performance issue', 'code review', 'production problem', 'scaling concerns', 'best practices', 'technical debt', 'refactoring strategy'. Essential for complex enterprise apps, critical production debugging, architectural refactors, or when choosing between competing technical approaches.

日本語の概要は準備中です。原文の説明を表示しています。

Poorgramer-Zack/dart-expert-skills72026年8月11日 更新

Builds SEO-friendly web applications with Dart using the Jaspr framework. Use when creating Dart-based websites, blogs, or landing pages requiring semantic HTML output; implementing server-side rendering (SSR) or static site generation (SSG); adding Tailwind CSS via jaspr_tailwind; routing with jaspr_router; testing components with jaspr_test; or building full-stack Dart web apps where Flutter Web's canvas rendering is unsuitable.

日本語の概要は準備中です。原文の説明を表示しています。

Poorgramer-Zack/dart-expert-skills72026年8月11日 更新

shadcn_flutter UI component library for building accessible, themed Flutter interfaces. Use when integrating shadcn components, configuring design system theming, or building consistent widget layouts.

日本語の概要は準備中です。原文の説明を表示しています。

Poorgramer-Zack/dart-expert-skills72026年8月11日 更新

Configures Codemagic CI/CD pipelines for Flutter using `codemagic.yaml`. Use when setting up automated Flutter builds on Codemagic, configuring iOS code signing without Fastlane Match, deploying to App Store Connect or Google Play from Codemagic, caching pub dependencies in Codemagic, setting up encrypted environment variable groups, running tests with Codemagic's test dashboard, or choosing between Codemagic and GitHub Actions + Fastlane for a Flutter CI/CD pipeline.

日本語の概要は準備中です。原文の説明を表示しています。

Poorgramer-Zack/dart-expert-skills72026年8月11日 更新

Poorgramer-Zack のスキルをすべて見る

このスキルの問題を報告する