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');
}
}
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;
}
}
You could try doing it this way though im usi IDS
//Declare as global variable
bool exist;
static Future<bool> checkExist(String docID) async {
try {
await Firestore.instance.document("users/$docID").get().then((doc) {
exist = doc.exists;
});
return exist;
} catch (e) {
// If any error
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With