1
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?

More than 1 year has passed since last update.

FreezedのFactory Constructor(Flutter)

Posted at

名前付き引数を使用し、エラーを防止

前回のおさらいとして、コンストラクタで定義されている引数の順番が違っても正しく割り当てて初期化してくれる機能がDartにはあります。

void main() {
  var dog = new Dog(animal: 'dogs', dog_breed: 'shiba');
}

class Dog {
  String dog_breed;
  String animal;

  Dog({required this.dog_breed, required this.animal});

  toString() => {
    '$dog_breed, $animal';
  }
}

requiredを引数に追加すれば、必須パラメータになります。次にapi用にデータクラスを用意します。

toJsonとfromJsonを持ったクラス

lib/views/dog.dart
class DogReq {
  final String animal;
  final String dog_breed;

  DogReq({
    this.animal = "",
    this.dog_breed = "",  
  });

  Map<String, dynamic> toJson() => {
        'animal': dogs,
        'dog_breed': shiba,
      };
}

class DogRes {
  final String animalRes;
  final String dogBreedRes;

  DogRes.fromJson(Map<String, dynamic> json)
      : animalRes = json['animal_response'],
        dogBreedRes = json['breed_response'];
}

freezedを使って書き換えてみる

lid/models/dog_json.dart
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';

  part 'auth.freezed.dart';
  part 'auth.g.dart';

@freezed
class DogReq with _$DogReq {
  const factory DogReq(
      {@JsonKey(name: 'dog_breed') required String shiba,
      @JsonKey(name: 'animal') required String dogs}) = _DogReq;

  factory DogReq.fromJson(Map<String, dynamic> json) =>
      _$DogReqFromJson(json);
}

@freezed
class DogRes with _$DogRes {
  const factory DogRes(
          {@JsonKey(name: 'animal_response') required String animalRes,
          @JsonKey(name: 'breed_response') required String dogBreedRes}) =
      _DogRes;

  factory DogRes.fromJson(Map<String, dynamic> json) =>
      _$DogResFromJson(json);
}

/models内にdog.freezed.dartdog.g.dartファイルを用意します。クラスに@freezedアノテーションを付与し、@JsonKeyでjson内のラベル名とクラス内の変数名をrequiredも付与して分けて使えるようにします。
fromJsonまで定義して下記コマンドでdog.freezed.dartdog.g.dartファイルを自動生成します。

flutter packages pub run build_runner build --delete-conflicting-outputs

--delete-conflicting-outputsオプションはdog.g.dartを削除してから再生成してくれます。

1
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
1
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?