flutter / dart如何检查Firestore中是否存在文档?

时间:2019-09-10 19:30:45

标签: flutter dart flutter-test

我尝试使用bool查询cloudfirestore中是否存在文档。不幸的是,我的代码无法正常工作

我尝试了以下操作,但bool并没有改变。

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

4 个答案:

答案 0 :(得分:6)

异步/等待功能以检查Firestore中是否存在文档(使用Flutter / Dart)

一个简单的异步/等待函数,您可以调用该函数来检查文档是否存在。返回true或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;
  }
}

答案 1 :(得分:1)

您可以尝试此方法对我有用

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

  }

答案 2 :(得分:0)

首先,您需要等待答案,然后,您总是从数据库中获得答案。这就意味着onexists确实存在。

您可以检查文档是否存在.documentID。像这样:

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

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

答案 3 :(得分:0)

您可以尝试通过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;
    }
  }
相关问题