Flutter : How to implement a callback

467

Solution 1

Try the following:

Future<AuthResult> login(String email, String password) async {
    try {
    Future<AuthResult> result = await FirebaseAuth.instance.signInWithEmailAndPassword(email: email, password: password);
    return result;
    } catch (e) {
      print(e);
    }
  }

Then you can call the method like this:

_submit() {
   // If fail to login then return the error message
   login(_email, _password).then((result) => {
      print(result);
  });
}

The method signInWithEmailAndPassword returns Future<AuthResult>, therefore assign it to that type, the await keyword will wait until the method finishes execution and then it will return the value of type Future<AuthResult>.

A future represents the result of an asynchronous operation, and can have two states: uncompleted or completed.

When you call the method login(), you can add the then() method which registers callbacks to be called when this future completes.

When this future completes with a value, the onValue callback will be called with that value.

https://api.dartlang.org/stable/2.7.0/dart-async/Future/then.html

Solution 2

  // wrapping the firebase calls
  Future<FirebaseUser> loginUser({String email, String password}) {
    return FirebaseAuth.instance
        .signInWithEmailAndPassword(email: email, password: password);
  }

the user info is returned, you not sure what you need the callback for?

 userInfo = await AuthService().loginUser(email: _email, password: _password);
Share:
467
YeN
Author by

YeN

Hello everyone.

Updated on December 16, 2022

Comments

  • YeN
    YeN over 1 year

    How to implement a callback return the error message?

    Login function from AuthService class:

    static void login(String email, String password) async {
        try {
          await FirebaseAuth.instance.signInWithEmailAndPassword(email: email, password: password);
        } catch (e) {
          print(e);
        }
      }
    

    Submit function from Login class:

    _submit() {
       // If fail to login then return the error message
       AuthService.login(_email, _password);
    }