【问题标题】:Flutter : How to implement a callbackFlutter:如何实现回调
【发布时间】:2019-12-22 20:26:06
【问题描述】:

如何实现回调返回错误信息?

AuthService 类的登录功能:

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

从登录类提交函数:

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

【问题讨论】:

    标签: firebase flutter dart callback


    【解决方案1】:

    尝试以下方法:

    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);
        }
      }
    

    然后你可以这样调用方法:

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

    方法signInWithEmailAndPassword返回Future&lt;AuthResult&gt;,因此将其分配给该类型,await关键字将等到方法执行完毕,然后返回Future&lt;AuthResult&gt;类型的值。

    Future 表示异步操作的结果,可以有两种状态:未完成或已完成。

    当您调用login() 方法时,您可以添加then() 方法,该方法注册回调以在此未来完成时调用。

    当这个未来以一个值结束时,onValue 回调将被调用并使用该值。

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

    【讨论】:

      【解决方案2】:
        // wrapping the firebase calls
        Future<FirebaseUser> loginUser({String email, String password}) {
          return FirebaseAuth.instance
              .signInWithEmailAndPassword(email: email, password: password);
        }
      

      返回了用户信息,你不确定你需要回调做什么?

       userInfo = await AuthService().loginUser(email: _email, password: _password);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-10
        • 2017-11-22
        • 1970-01-01
        • 1970-01-01
        • 2021-01-25
        • 1970-01-01
        • 1970-01-01
        • 2020-05-06
        相关资源
        最近更新 更多