flutter firestore_ref 3階層のコレクションをFactory constructorsで取得しやすくしてみる

/**
 * 親の親がorganizations,親がprojects
 */
class TeamsRef extends CollectionRef<Team, TeamDoc, TeamRef> {
  TeamsRef(this.cr) : super(cr);
  final CollectionReference<Map<String, dynamic>> cr;

  // 作ってみたもののあんまり意味がない
  factory TeamsRef.parentDoc(ProjectDoc doc) =>
      TeamsRef(doc.projectRef.ref.collection('teams'));

  // 呼び出し元が冗長
  factory TeamsRef.parentRef(ProjectRef parentRef) =>
      TeamsRef(parentRef.ref.collection('teams'));

  // 呼び出しもとは簡潔
  factory TeamsRef.ids(String grandParentId, String parentId) =>
      TeamsRef(FirebaseFirestore.instance
          .collection('organizations/$grandParentId/projects/$parentId/teams'));

  /* collectionGroupだと型が合わない
  factory TeamsRef.parentId(String parentId) =>
      TeamsRef(FirebaseFirestore.instance.collectionGroup(collectionPath));
  */

  @override
  JsonMap encode(Team data) => replacingTimestamp(json: data.toJson());

  @override
  TeamDoc decode(DocumentSnapshot<JsonMap> snapshot, TeamRef docRef) {
    return TeamDoc(
      docRef,
      Team.fromJson(snapshot.data()!),
    );
  }

  @override
  TeamRef docRef(DocumentReference<JsonMap> ref) => TeamRef(
        ref: ref,
        teamsRef: this,
      );
}

factoryコンストラクタをこんな風に使っていいかはわかってないですが、 一応期待通り動きます。

flutter_firestore_practice/team.dart at main · na8esin/flutter_firestore_practice · GitHub