以下代码可以正常工作,因为它仅返回一个简单列表,但是在某些情况下,我需要执行嵌套Firebase调用,因此无法按正确的顺序进行操作,并且主return语句不完整。我该怎么做才能改善我的 future 异步 call ?
Future<List<MyNotification>> getNotifications() async {
var uid = await FirebaseAuth.instance.currentUser();
List<MyNotification> tempNots = await Firestore.instance
.collection("notifications")
.where("targetUsers", arrayContains: uid.uid)
.getDocuments()
.then((x) {
List<MyNotification> tempTempNots = [];
if (x.documents.isNotEmpty) {
for (var not in x.documents) {
tempTempNots.add(MyNotification.fromMap(not));
}
}
return tempTempNots = [];
});
return tempNots;
}
最佳答案
最重要的事情;不要在异步函数中使用then
。我这样修改了您的代码;
Future<List<MyNotification>> getNotifications() async {
// Using the type definition is better.
FirebaseUser user = await FirebaseAuth.instance.currentUser();
// The return type of getDocuments is a QuerySnapshot
QuerySnapshot querySnapshot = await Firestore.instance
.collection("notifications")
.where("targetUsers", arrayContains: user.uid)
.getDocuments();
List<MyNotification> tempTempNots = [];
if (querySnapshot.documents.isNotEmpty) {
for (DocumentSnapshot not in querySnapshot.documents) {
tempTempNots.add(MyNotification.fromMap(not));
}
}
return tempTempNots;
}
关于flutter - 在未来的异步调用中,我需要一些指导,包括 flutter 和 Dart ,有时情况会发生困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61278809/