问题
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