3
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 × Firestore 追加、更新、取得

Last updated at Posted at 2021-07-11

値を追加する

Firebaseのusersコレクションのフィールド値に値を追加したいときは以下のように書きます。
今回はnameというフィールド値に名無しのごんべを追加します。* addは任意のドキュメントIDが生成されます


FirebaseFirestore.instance.collection('users').add({
      'name' : '名無しのごんべ'
});

スクリーンショット 2021-08-28 12.06.00.png

setはドキュメントIDを指定して追加・一括更新をすることができます。


FirebaseFirestore.instance.collection('users').doc(uid).set({
      'name' : '名無しのごんべ'
});

値を更新する

フィールド値を更新するには doc(uid) とドキュメントIDを指定してkeyにフィールド値、valueに追加したい値を挿入します。


FirebaseFirestore.instance.collection('users').doc(uid).update({
    'name' : 'ymktmk'
});

値を取得する

QuerySnapshotは複数のドキュメントIDを取得することができます。複数のドキュメントIDを1個ずつforEachで回しています。


FirebaseFirestore.instance.collection('users').get().then((QuerySnapshot snapshot) {
   snapshot.docs.forEach((doc) {
     /// usersコレクションのドキュメントIDを取得する
     print(doc.id);
     /// 取得したドキュメントIDのフィールド値nameの値を取得する
     print(doc.get('name'));
   });
});

DocumentSnapshotは単一のドキュメントIDを取得します。そのため doc(uid) とドキュメントIDを指定します


FirebaseFirestore.instance.collection('users')
     .doc(uid).get().then((DocumentSnapshot snapshot) {
     print(snapshot.get('name'));
});

リアルタイムに取得する

リアルタイムで取得するときにはgetではなくsnapshotをつけます。


FirebaseFirestore.instance.collection('users')
   .snapshots().listen((QuerySnapshot snapshot) {
     snapshot.docs.forEach((doc) { 
       print(doc.get('name'));
     });
});


FirebaseFirestore.instance.collection('users')
      .doc(myId).snapshots().listen((DocumentSnapshot snapshot) {
      print(snapshot.get('name'));
});

StreamBuilderを使う

ぶっちゃけStreamBuilderを使ってリアルタイムでViewに表示させるのがいいかもし れません


class Example extends StatelessWidget {

  final myId = FirebaseAuth.instance.currentUser!.uid;

  @override
  Widget build(BuildContext context) {

    return StreamBuilder<DocumentSnapshot>(
        stream: FirebaseFirestore.instance.collection('users').doc(myId).snapshots(),
        builder: (BuildContext context,  AsyncSnapshot<DocumentSnapshot> snapshot) {
          if (snapshot.hasData) {
            return Text(snapshot.data!['name']);
          } else {
            return Container();
          }
        }
    );
  }

}

以下のようにも書くことができます。stream: MeetController.getMatch(), ではStream>を返すようなモデルを作成すればOKです。


class Example extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<List<RoomModel>>(
      stream: MeetController.getMatch(),
      builder: (BuildContext context, AsyncSnapshot<List<RoomModel>> snapshot) {

        print(snapshot.data![0].roomId);
             
      }
    );
  }
}

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