我有3个函数,doesNameAlreadyExist
检查文档是否存在。顺便说一句,我对这些方法的改进持开放态度。
Future<bool> doesNameAlreadyExist(String name) async {
QuerySnapshot queryDb = await Firestore.instance
.collection('locations')
.where("city", isEqualTo: '${name}')
.limit(1)
.getDocuments();
final List<DocumentSnapshot> documents = queryDb.documents;
return documents.length == 1;
// I have to return DocumentReference if document is exists,
// Even though, it's not on the scope of this particular problem,
// I'm open to ideas. Maybe I can return a map, bool and reference combined
}
这个在firestore上推文件。
Future<DocumentReference> pushNameToFirestore(PlaceDetails pd) async {
Future<DocumentReference> justAddedRef = Firestore.instance.collection('locations').add(<String, String>{
'city': '${pd.name}',
'image': '${buildPhotoURL(pd.photos[0].photoReference)}',
});
return justAddedRef;
}
在这里,我正在检查,然后推动上述功能。但是我无法返回文档参考。
DocumentReference firestoreCheckAndPush() async {
bool nameExists = await doesNameAlreadyExist(placeDetail.name);
// TODO notify user with snackbar and return reference
DocumentReference locationDocumentRef;
if(nameExists) {
print('name exist');
} else {
locationDocumentRef = await pushNameToFirestore(placeDetail);
}
return locationDocumentRef; // Error is here
}
我认为这里的问题是你不等待你的DocumentReference
,所以你返回一个Future
而不是实际预期的DocumentReference
。
试试这个:
Future<DocumentReference> pushNameToFirestore(PlaceDetails pd) async {
DocumentReference justAddedRef = await Firestore.instance.collection('locations').add(<String, String>{
'city': '${pd.name}',
'image': '${buildPhotoURL(pd.photos[0].photoReference)}',
});
return justAddedRef;
}
这是一篇关于未来和异步的好文章:Link to the article
希望它的帮助!!