skip to Main Content

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


  1. Most likely an error occurs in your updateUser function.

    When you just call DbHelper.updateUser(user) without await, the call is started on that line – but the rest of the code in deleteFindRequest doesn’t wait for its completion – so it also executes.

    When you call await DbHelper.updateUser(user), you’re telling it to wait until updateUser is done before executing the rest of the code. And since updateUser 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"

    Future<bool> deleteFindRequest(UserAccount user) async {
      try {
        userAccount!.findsRequest.removeWhere((element) => element['uid'] == user.uid);
        findsRequestList.removeWhere((element) => element.uid == user.uid);
        user.findsRequested.removeWhere((element) => element == userAccount!.uid);
        await DbHelper.updateUser(user);
        updateActualUser();
        notifyListeners();
        return true;
      }
      catch (e) {
        print(e);
      }
    }
    
    Login or Signup to reply.
  2. 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

    await FirebaseFirestore.instance
          .collection(collectionUser)
          .doc(userAccount.uid)
          .update(userAccount.toJson());
    

    above declaration in a variable by making it nullable

    then add a condition

    if(variable != null){
      return true;
    }else{
     return false;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search