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

|▌冷眼眸甩不掉的悲伤 提交于 2020-05-31 14:46:23

问题


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');
  }
}

回答1:


you could try doing it this way though im usi IDS

static Future<bool> checkExist(String docID) async {
    bool exists = false;
    try {
      await Firestore.instance.document("users/$docID").get().then((doc) {
        if (doc.exists)
          exists = true;
        else
          exists = false;
      });
      return exists;
    } catch (e) {
      return false;
    }
  }



回答2:


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);
}



回答3:


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;
   }

  }


来源:https://stackoverflow.com/questions/57877154/flutter-dart-how-can-check-if-a-document-exists-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!