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

Time:06-17

I want to check if a field exists in a document in firebase firestore or not.

CodePudding user response:

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='';

          }

        }

      }

    });

CodePudding user response:

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(),
                );
              },
            ),
  • Related