I am writing a function to delete friend requests from my application. To save data to my database, I use the DbHelper.update(user)
function, which allows me to store my data in the database.
Here my functions:
Future<bool> deleteFindRequest(UserAccount user) async {
userAccount!.findsRequest.removeWhere((element) => element['uid'] == user.uid);
findsRequestList.removeWhere((element) => element.uid == user.uid);
user.findsRequested.removeWhere((element) => element == userAccount!.uid);
DbHelper.updateUser(user);
updateActualUser();
notifyListeners();
return true;
}
static Future<bool> updateUser(UserAccount userAccount) async {
await FirebaseFirestore.instance
.collection(collectionUser)
.doc(userAccount.uid)
.update(userAccount.toJson());
return true;
}
However, when I put await
in front of DbHelper.update(user)
, the data does not get saved, but when I remove it, it works. I don’t understand how adding await
here changes the execution of my function. If someone could provide some guidance, it would be a great help.
2
Answers
Most likely an error occurs in your
updateUser
function.When you just call
DbHelper.updateUser(user)
withoutawait
, the call is started on that line – but the rest of the code indeleteFindRequest
doesn’t wait for its completion – so it also executes.When you call
await DbHelper.updateUser(user)
, you’re telling it to wait untilupdateUser
is done before executing the rest of the code. And sinceupdateUser
actually never succeeds, the rest of the code never executes.The simplest way to see this sort of problem is by always having a
try
/catch
so that errors get caught. For example"The problem is that your function (updateUser) directly returns true, even if the future is in progress.
try checking first if the future has been completed by storing
above declaration in a variable by making it nullable
then add a condition