我有一个在其中调用Future的函数。现在我不确定第一个函数是否也需要等待数据的未来。下面是我的代码:
FireBaseHandler handler = FireBaseHandler();
saveRows() {
handler.saveRows(plan.planId, plan.rows); ///this is a future
}在我的FireBaseHandler类中,我有这样的未来:
final CollectionReference usersCol =
FirebaseFirestore.instance.collection('users');
Future saveRows(String id, data) async {
return await usersCol.doc(myUser.uid).collection('plans').doc(id)
.update({'rows': data});
}那么第一个函数也需要是一个未来吗?
发布于 2021-10-01 14:26:48
您可以在sync函数中使用async函数。但是这样你就失去了对结果执行await的能力。并且只允许在标记为async的函数中使用await,这会将我们引向该函数的结果Future。所以,是的,如果你需要等待结果,两个函数都必须是Future函数。
编辑:如果您需要包装器函数为sync,但仍然能够从内部async函数检索结果,则可以使用回调:
saveRows(Function(dynamic) callback) {
handler.saveRows(plan.planId, plan.rows).then((result){
callback(result);
});
}这样,在调用函数后的任何时间点都会检索到结果(代码不是await格式的)
https://stackoverflow.com/questions/69407401
复制相似问题