Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
  }
}
like image 644
Livio98 Avatar asked Sep 10 '19 19:09

Livio98


Video Answer


2 Answers

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;
  }
}
like image 72
Matthew Rideout Avatar answered Nov 13 '22 00:11

Matthew Rideout


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;
    }
}
like image 20
griffins Avatar answered Nov 13 '22 00:11

griffins