I have a function that calls a Future in it. Now I am not sure if the first function needs to be a future too to await for the data. Here is my code:
FireBaseHandler handler = FireBaseHandler();
saveRows() {
handler.saveRows(plan.planId, plan.rows); ///this is a future
}
In my FireBaseHandler class I have this Future:
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});
}
So does the first function needs to be a Future too?
CodePudding user response:
You can have async
function inside a sync
function. But this way you lose ability to await
for the result. And await
is allowed only in functions marked as async
, which leads us to Future
as a the result of that function. So, yes, if you need to wait for the result, both functions have to be Future
functions.
Edit:
If you need your wrapper function to be sync
, but still be able to retrieve the result from inner async
function, you can use a callback:
saveRows(Function(dynamic) callback) {
handler.saveRows(plan.planId, plan.rows).then((result){
callback(result);
});
}
This way the result will be retrieved at any point of time after calling the function (the code is not await
ed)