0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

freezeの使い方

Last updated at Posted at 2025-10-15

1. 必要なdependenciesを追記する

pubspec.yaml
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  freezed_annotation: ^3.1.0 #追加(最新verを指定すること)

dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner: ^2.9.0 #追加(最新verを指定すること)
  freezed: ^3.2.3 #追加(最新verを指定すること)
  • freezed_annotation build_runner freezedの3つのパッケージが必要となる。記載例は2025年10月15日時点での最新パッケージだが、各ホームページを参照して最新のバージョンを指定すること。

2. パッケージをインストール

Terminal.
> flutter pub get

3. パッケージのimport

titles.dart
import 'package:freezed_annotation/freezed_annotation.dart';

4. partを記載する

titles.dart
part '{yourModelName}.freezed.dart';
  • URIは存在しないと赤波線でエラーが発生するがひとまず無視で問題ない。

5. クラスに@freezedアノテーションを付ける

titles.dart
@freezed // 追加
class Title {
  • ネストしていたり同ファイルの中に複数のClassがある場合にはすべてのクラスの上に@freezedアノテーションを付与しておく。

6. classをwithメソッドに対応させる

titles.dart
@freezed
class Title with _$Title { // 変更
  • Classの名前に_$をセットする

7. const Factory({})でパラメータを囲う

titles.dart
@freezed
class Title with _$Title {
  const factory Title({
    required String title,
    required Cover cover,
    required Content content,
  }) = _Title;
}
  • 最後に= _Title;を記載することを忘れない。

8. freezedファイルの自動生成

Terminal.
> flutter pub run build_runner build
  • 参考

9. モデルと同じディレクトリに.freezed.dartファイルが生成されている

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?