我正在尝试在包含侦听器的函数上实现未来的回报。当侦听器至少返回一次数据时,我想完成此将来的操作。我没有使用async / await,因为监听功能不再适用。因此,我的选择如下:
static Future listenForConsumption() async {
Completer completer = Completer();
try {
kConsumptionCollection
.where("userId", isEqualTo: User.current.id)
.orderBy("consumptionDate", descending: true)
.snapshots()
.listen(
(data) {
consumptionList = data.documents
.map((doc) => ConsumptionUnit.data(doc.documentID, doc.data))
.toList();
streamController.add(consumptionList);
completer.complete();
},
);
} catch (err) {
completer.complete();
throw (err);
}
return completer.future;
}
通过使用完成器,我试图等待侦听器完成。但是,调用此函数的函数似乎并不在等待将来完成:
void _checkForCurrentUser() async {
try {
await UserManager.fetchCurrentUser(); //Function waits for this
await Future.wait([
ConsumptionManager.listenForConsumption(),
BottleManager.listenForBottles(),
]); //Function does not wait for this
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Home()),
);
} catch (err) {
log("$err");
}
//...Rest of function
有什么想法可以遗漏吗?
答案 0 :(得分:0)
使用类似这样的内容:
static void listenForConsumption(
{ @required Function onComplete,
@required Function onError,
}) async {
try {
kConsumptionCollection
.where("userId", isEqualTo: User.current.id)
.orderBy("consumptionDate", descending: true)
.snapshots()
.listen(
(data) {
consumptionList = data.documents
.map((doc) => ConsumptionUnit.data(doc.documentID, doc.data))
.toList();
onComplete(consumptionList);
},
);
} catch (err) {
onError(err);
}
}