[英]How to solve “The return type 'DocumentReference ()' isn't a 'DocumentReference ()', as defined by the method” error?
I have 3 functions, doesNameAlreadyExist
checks whether a document is exists or not. 我有3个函数,
doesNameAlreadyExist
检查文档是否存在。 I'm open to any improvement on those methods by the way. 顺便说一句,我对这些方法的改进持开放态度。
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
}
This one pushes document on firestore. 这个在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;
}
And here, I'm checking and then pushing with those functions above. 在这里,我正在检查,然后推动上述功能。 However I can't return the document reference.
但是我无法返回文档参考。
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
}
I think the problem here is that you don't wait for your DocumentReference
, so you return a Future
instead of a DocumentReference
which is actually expected. 我认为这里的问题是你不等待你的
DocumentReference
,所以你返回Future
而不是实际预期的DocumentReference
。
Try this: 尝试这个:
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;
}
Here's a great article about future and async : Link to the article 这是一篇关于未来和异步的精彩文章: 链接到文章
Hope it's help !! 希望它的帮助!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.