👋
Flutter:Factory(コンストラクタ)について
はじめに
Firestoreの公式資料で,Dart(Flutter)のサンプルコードでfactory
と呼ばれる修飾子が使われていたので気になって調べてみることにしました.
- 対象のサンプルコードがこちら(一部抜粋)
class City {
final String? name;
final String? state;
final String? country;
final bool? capital;
final int? population;
final List<String>? regions;
City({
this.name,
this.state,
this.country,
this.capital,
this.population,
this.regions,
});
// これ↓!!!!!!!
factory City.fromFirestore(
DocumentSnapshot<Map<String, dynamic>> snapshot,
SnapshotOptions? options,
) {
final data = snapshot.data();
return City(
name: data?['name'],
state: data?['state'],
country: data?['country'],
capital: data?['capital'],
population: data?['population'],
regions:
data?['regions'] is Iterable ? List.from(data?['regions']) : null,
);
}
...
}
どういう時,使うのか?
公式資料では,以下2つの場合にfactory
を使うと述べている.
-
クラスの新しいインスタンスを作成するとは限らない時
- この場合,(1)キャッシュから既存のインスタンス,または(2)サブタイプの新しいインスタンスを返す.
↑他記事で述べられているシングルトン作成したい時等は,これに該当すると思われる.
- インスタンス作成前に,何か重要な処理(引数のチェックや,initializer listでは対応しきれない処理)が必要な場合
↑Firestoreのサンプルコードは,これに該当する
その他特徴
this
は使えない- 返り値有りの関数のように,
return
文が必要
参考資料
Discussion