💬

freezedの使い方+JsonKey

2023/06/21に公開

Freezedを使ってみる。

  • 依存関係の追加
pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  freezed_annotation: ^2.2.0
  json_annotation: ^4.8.0 //JsonKeyで使う
  

dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner: ^2.4.5
  freezed: ^2.3.5
  json_serializable: ^6.7.0
  • modelを追加する。
chair_model.dart
import 'package:freezed_annotation/freezed_annotation.dart';


part 'chair_model.freezed.dart';
part 'chair_model.g.dart';


class ChairModel with _$ChairModel {
  factory ChairModel() = _ChairModel;

  factory ChairModel.fromJson(Map<String, dynamic> json) =>
      _$ChairModelFromJson(json);
}
terminal
flutter pub run build_runner build
flutter pub run build_runner watch

これら2つが生成される
chair_model.freezed.dart
chair_model.g.dart

JsonKeyの使ってみよう

JsonKeyを使わない

noJsonKey
class foo extends _$foo{
 const factory foo({
   required int id,
   ('dafaultName') String name,
   required int age,
 })
}

生成されたファイルを詳しく見てみると

foo.g.dart
_$_FooModel _$$_FooModelFromJson(Map<String, dynamic> json) => _$_FooModel(
      id: json['id'] as int,
      name: json['name'] as String? ?? 'dafaultName',
      age: json['age'] as String,
    );

Map<String, dynamic> _$$_FooModelToJson(_$_FooModel instance) =>
    <String, dynamic>{
      'id': instance.id,
      'name': instance.name,
      'age': instance.age,
    };

JsonKeyを使ってみる

useJsonKey
class foo extends _$foo{
 const factory foo({
   (name='user_id')required int id,
   ('dafaultName') String name,
   required int age,
 })
}
foo.g.dart
_$_FooModel _$$_FooModelFromJson(Map<String, dynamic> json) => _$_FooModel(
      id: json['user_id'] as int,// keyが変化
      name: json['name'] as String? ?? 'name',
      age: json['age'] as String,
    );
  • JsonKeyの他のField
JsonKey JsonKey({
  bool? nullable,//nullを許容するか
  Object? defaultValue,//デフォルトの値
  bool? disallowNullValue,
  Function? fromJson,//decodeする際に、処理を挟むとき
  bool? includeFromJson,//fromJsonにfieldを追加するのか
  bool? includeIfNull,
  bool? includeToJson,//toJsonにfieldの追加するのか
  String? name,//jsonのkeyに対応するするkey
  Object? Function(Map<dynamic, dynamic>, String)? readValue,
  bool? required,//fieldが必須になる
  Function? toJson,//encodeする際に、処理を挟むとき
  Enum? unknownEnumValue,
})

Discussion