4
3

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 3 years have passed since last update.

【Flutter】FirebaseAuthでユーザ登録した後にuidでFirestoreにコレクションとサブコレクションを作る例

Posted at

FirebaseのCloud Firestoreにユーザ登録して、usersフィールドにuidでドキュメント作って
その下にサブコレクションを作るコードメモ

signUpAndGenerateSubCollection.dart
Future signUpAndGenerateSubCollection() async {
    try {
      // メールとパスワードでユーザー登録
      final FirebaseAuth auth = FirebaseAuth.instance;
      final AuthResult result = await auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
      // 登録したユーザー情報
      final FirebaseUser user = result.user;
      final users = Firestore.instance.collection('users');
      collection.document(user.uid).collection('hoge').add({
        'hoge': hoge,
      });
    } catch (e) {
      // 登録に失敗した場合
      throw (e);
    }
  }

新規登録の後に新しく作る場合

adHoge.dart

Future addHoge() async {
    final FirebaseAuth auth = FirebaseAuth.instance;
    final users= Firestore.instance.collection('users');
    final user = await auth.currentUser();
    if (user != null) {
      users.document(user.uid).collection('hoge').add({
        'hoge': hoge,
      });
    }
  }

ユーザが個別の記事などを投稿する場合、サブコレクションを実装したほうが後々よさそう。

参考:

Cloud Firestoreの勘所 パート2 — データ設計(https://medium.com/google-cloud-jp/firestore2-920ac799345c)

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?