Wait for an asynchronous function to finish to continue

Asked

Viewed 270 times

-2

I can expect an asynchronous terminal function to continue the code?

I have an asynchronous function with a Try/catch and want to catch the bug to treat.

Login(BuildContext context) async { 
try {
      FirebaseUser _login = (await FirebaseAuth.instance
              .signInWithEmailAndPassword(email: email, password: pass))
          .user;

      if (_login != null) {
        userid = _user.uid;
        Modular.to.pushNamed('/inicial');
      }
    } catch (e) {
      msge = e.code;
    }
  }

When I call the function and try to get the msge it returns null, I did some tests and from what I understand it returns null because it has not yet finished.

Is there any way to take this data?

  • An asynchronous function always returns an object of type Future. The operator await awaits resolution of that Future and takes the result of it. If you are receiving null, then null is the result of Future, you are waiting correctly, the result is that it is empty even.

  • But this function I use to check the right login? When the email is wrong firebase returns 'EMAIL_INVALID' which is e.code, but what should be happening is, when it arrives at msge = e.code o e.code is null because await has not returned yet. Would that be?

1 answer

1

Just remembering, the functions should always start with lowercase letters (Lower-case).

Regarding your problem, I believe you’re trying to capture the user before function signInWithEmailAndPassword return something, so trying to access the value of a null variable will cause another error other than firebase validation.

Try to modify your function as follows:

  void login(BuildContext context) async { 
    final FirebaseAuth firebaseAuth = FirebaseAuth.instance;

    try {
      await firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
      FirebaseUser user = await firebaseAuth.currentUser();

      if (user != null) {
        userid = user.uid;
        Modular.to.pushNamed('/inicial');
      }
    } catch (e) {
      msge = e.code;
    }
  }

Your property msge will only receive a value if the signInWithEmailAndPassword() returns some of the pre-defined errors in the package.

Explaining

The await causes the application to wait for the asynchronous call to end so that the execution of that function block continues.

So if you’re using the property msge in another place, most likely it is being returned NULL because there is no time to be fed by the method login.

  • 1

    Cara thanks for the explanation and the touches, I think I got bored, I call this function in another file but I think my mistake is to call the function and then give the debugPrint(login.msge) and leave null, I believe the error is there, I’m gonna try to study it and see if I can find what it might be.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.