'flutter / dart How can check if a document exists in firestore?

I try to query using a bool if a document exists on the cloudfirestore or not. Unfortunately, my code does not work

I tried the following, but the bool does not change.

getok() {
  bool ok;
  Firestore.instance.document('collection/$name').get().then((onexist){
      onexist.exists ? ok = true : ok = false;
    }
  ); 
  if (ok = true) {
    print('exist');
  } else {
    print('Error');
  }
}


Solution 1:[1]

Async / Await Function To Check If Document Exists In Firestore (with Flutter / Dart)

A simple async / await function you can call to check if a document exists. Returns true or false.

bool docExists = await checkIfDocExists('document_id');
print("Document exists in Firestore? " + docExists.toString());

/// Check If Document Exists
Future<bool> checkIfDocExists(String docId) async {
  try {
    // Get reference to Firestore collection
    var collectionRef = Firestore.instance.collection('collectionName');

    var doc = await collectionRef.document(docId).get();
    return doc.exists;
  } catch (e) {
    throw e;
  }
}

Solution 2:[2]

You could try this it works for me

Future getDoc() async{
   var a = await Firestore.instance.collection('collection').document($name).get();
   if(a.exists){
     print('Exists');
     return a;
   }
   if(!a.exists){
     print('Not exists');
     return null;
   }

  }

Solution 3:[3]

First you need to wait for the answer and second you always get an answer from the database. That means onexists does always exist.

You can check if the document exists with .documentID. Something like that:

try {
  var res = await Firestore.instance.document('collection/$name').get();
  print(res.documentID ? 'exists' : 'does not exist');

} catch (err) {
  print(err);
}

Solution 4:[4]

This answer checks if a document exit, and seek to update it with new data if it does exist. The below sample code is written in Flutter(dart).

Future uploadDataToFirestore(String docID) async {
var docSnapshot = await checkIfDocExist(docID);
if(docSnapshot.exists){
  try {
    await docSnapshot.reference.update(newData.toMap());
  } catch (e) {
    // TODO: Handle catched error here
  }
}
else{
  // TODO: execute some code here
}

}

Future<DocumentSnapshot<Object?>>checkIfDocExist(String docID) async { try {

  var doc = await collectionRef.doc(docID).get();
  return doc;
} catch (e) {
  rethrow;
}

}

Solution 5:[5]


  Future<bool> documentExistsInCollection(String collectionName, String docId) async {
    try {
      var doc =
          await FirebaseFirestore.instance.collection(collectionName).doc(docId).get();
      return doc.exists;
    } catch (e) {
      throw e;
    }
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthew Rideout
Solution 2 Saurabh Pandey
Solution 3 Neli
Solution 4
Solution 5 Akash g krishnan