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

【Flutter】freezedで記述するfactoryコンストラクタについて

Posted at

freezedで定義するfactoryコンストラクタ

riverpodを利用する際に、簡単にモデル定義できるfreezed。
具体的な中身の仕組みを理解してみようと見たところ、①の_Personが何を意味しているのか気になったので調べました。
結論を言うと、「factoryコンストラクタのリダイレクト(_Personのインスタンスを返す)」を表しています。

@freezed
abstract class Person with _$Person {
  const factory Person({
    required String firstName,
    required String lastName,
    required int age,
  }) = _Person;                          // ①

  factory Person.fromJson(Map<String, Object?> json) => _$PersonFromJson(json);
}

factoryコンストラクタ

Personはfactoryコンストラクタで定義されています。
factoryコンストラクタの特徴は以下の通り。

  • 自分自身のインスタンスではなく、他のインスタンスを返すコンストラクタ
  • nullを返すことができず、インスタンスを明示する必要がある

しかしここではインスタンスが返されていません。
その代わりに、_Personへリダイレクトするよう定義されています。

factoryコンストラクタのリダイレクト

class A {
  factory A() = B; // リダイレクト(引数もそのまま渡す)
}
class B extends A {
  const B(); 
}

「=リダイレクト先のクラス名」とすることで、同じサブタイプの別のクラスへリダイレクトすることができます。
リダイレクトを設定することで、Personで定義した引数をそのまま_Personへ渡してくれるため、コードが簡潔になります。

同クラスのコンストラクタへのリダイレクト

上記とは別に、リダイレクトとしてコロンを利用する方法があります。
同じクラス内の別のコンストラクタにリダイレクトする場合は以下のように「: this...」と記述します。

class Point {
  double x, y;

  // The main constructor for this class.
  Point(this.x, this.y);

  // Delegates to the main constructor.
  Point.alongXAxis(double x) : this(x, 0);
}

参考

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