flutter - 我需要一些关于 Flutter 和 dart 的未来异步调用的指导,有时事情会发生混乱
问题描述
下面的代码工作正常,因为它只返回一个简单的列表,但在某些情况下,我需要进行嵌套的 Firebase 调用,我无法让事情以正确的顺序发生,并且主要的 return 语句不完整。我可以做些什么来改进我的未来异步调用?
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;
}
推荐阅读
- r - 根据列表中数据框的文件名在大列表中设置数据子集
- r - 理解和重建数据帧重载为 d3 格式
- c# - 如何在邮件模板中使用 App.Resources
- android - 如何发送包含字符串数组和文件数组的多部分
- git - 在 Katalon 工作室 GitHub 集成中创建新分支
- python-3.x - 无法使用 beautifulsoup 刮取表格的所有行
- swift - 有没有办法让 @Published 属性实际上得到更新和发布?
- python - Selenium 在无头模式 Ubuntu 18.04 中无法通过 xpath 获取元素
- python - Scrapy - 如何在已启用 cookie 时修复“请启用 cookie”?
- c++ - 两个元素之间的字节