简体   繁体   中英

FlutterFire | How can you check if a field exists in a document/documentSnapshot or not?

我想检查 firebase firestore 的文档中是否存在字段。

FirebaseFirestore.instance.collection('Products').doc(barcode).get().then((value) {

      if (value.data() !=null) {

        if (value.data().length>0) {

          /// Here I am checking if the field Trigram exist  <==///

          if (value.data()['Trigram']!=null) {

             searchTrigram=value.data()['Trigram'];

          } else {

             searchTrigram='';

          }

        }

      }

    });

Try this follow demo:

await fireStore
        .collection(AppConfig.instance.cUser)
        .doc(event.userId)
        .get()
        .then(
      (DocumentSnapshot documentSnapshot) {
        if (documentSnapshot.exists) {
          var data = documentSnapshot.data();
          var res = data as Map<String, dynamic>;
          
        } else {
          //do something
        }
      },
    );

And if you use in StreamBuilder :

StreamBuilder<QuerySnapshot>(
              stream: FirebaseFirestore.instance
                  .collection(AppConfig.instance.cUser)
                  .doc(AppConfig.instance.cListChat)
                  .collection(widget.userId)
                  .orderBy('create_at', descending: true)
                  .snapshots(),
              builder: (BuildContext context,
                  AsyncSnapshot<QuerySnapshot> chatSnapshot) {
                if (chatSnapshot.connectionState == ConnectionState.waiting) {
                  return Center(
                    child: Container(),
                  );
                }
                return ListView(
                  reverse: true,
                  controller: _controller,
                  physics: const BouncingScrollPhysics(),
                  children:
                      chatSnapshot.data!.docs.map((DocumentSnapshot document) {
                    if(document.exists){
                      Map<String, dynamic> data =
                      document.data()! as Map<String, dynamic>;
                      var _chat = ChatData.fromJson(data);
                      return Container();
                    } else {
                      return Container();
                    }
                  }).toList(),
                );
              },
            ),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM