Himanshu Ranjan
Himanshu Ranjan

Reputation: 302

How to check whether a document exists or not in cloud firestore for flutter?

I want to check whether a document in the firestore exists or not using the snapshot, I am getting a red screen error returning null when I try to fetch a non existing document.

StreamBuilder(
              stream: Firestore.instance
                  .collection('Resumes')
                  .document(uid)
                  .snapshots(),
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Center(child: CircularProgressIndicator());
                }; 

How do i check whether the document with name uid exists or not?

Upvotes: 1

Views: 2811

Answers (4)

Nand gopal
Nand gopal

Reputation: 346

snapshot.hasData returns true even if the specified document does not exist in the collection.

To check if the document exists, you can check if snapshot.data.data==null

So, you'd have to change your code to:

StreamBuilder(
          stream: Firestore.instance
              .collection('Resumes')
              .document(uid)
              .snapshots(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              if(snapshot.data.data==null){
                 
                 //document does not exist

              }
              else{

                 //document exists

              }


            } else{
               
              //Waiting for data 
              return Center(child: CircularProgressIndicator());

             }  
            };

Upvotes: 2

Biruk Telelew
Biruk Telelew

Reputation: 1193

var res=Firestore.instance .collection('Resumes').documents;
if(res==null){
  print("no documents found");
}else{
  //there are documents
}

set the collection instance to a variable and check that if the variable is null or not using if statement.

Upvotes: 0

Morez
Morez

Reputation: 2229

You can use exists method on the document snapshot to check whether the document exists or not:

DocumentSnapshot docSnapshot = await Firestore.instance.collection('Resumes').document(uid).get();
bool isDocExists = docSnapshot.exists(); //true if exists and false otherwise

Upvotes: 2

Scott Godfrey
Scott Godfrey

Reputation: 671

Instead of document('uid') do this:

 Firestore.instance .collection('Resumes').documents;

Then you can iterate through the documents checking for a match to the documentId property.

final document = snapshot.data.firstWhere((doc) => doc.documentId = uid, orElse: () => null)

Then, check if document != null

Upvotes: 1

Related Questions