flutter - 有没有办法在 Flutter 中的小部件内使用 catch 块的结果

我正在构建一个以 Firebase 作为后端的 flutter 应用程序。我在一个单独的文件上创建了一个 AuthService 类,并在登录屏幕中导入和使用 Auth 函数。

这是我的 AuthService 类。

class AuthService {
  Future<UserModel?> signInWithEmailAndPassword(
      String email, String password) async {
    try {
      final cred = await _auth.signInWithEmailAndPassword(
          email: email, password: password);

      return _userFromFirebase(cred.user);
    } on auth.FirebaseAuthException catch (e) {
      print(e.toString());
      return null;
    }
  }
}

在登录页面中,我初始化了函数:

final auth = Provider.of<AuthService>(context);

然后在 onPressed 中使用它:

press: () async {

                            // SIGN IN WITH EMAIL AND PASSWORD
                            dynamic result =
                                await auth.signInWithEmailAndPassword(
                                    email, password);

                            // IF SIGN IN FAILS
                            if (result == null) {
                              setState(() {
                                errorSigningIn = 'Sign in error';
                                //this is where I want to use the error response. 
                              });
                            }
                          },

我坚持使用我在 signInWithEmailAndPassword 函数中捕获的错误并将其分配给 SignIn 小部件中的 errorSigningIn 变量。

我是新手,请帮忙。

谢谢。

回答1

您可以创建自己的类来处理身份验证结果。例如:

class AuthResult {
    final int code;
    final UserModel? user;
    final String? errorMessage;

    AuthResult(this.code, {
        this.user,
        this.errorMessage,
    });
}

此类可以帮助您处理所有登录情况。这就是您应该对登录方法执行的操作:

class AuthService {
  Future<AuthResult> signInWithEmailAndPassword(
      String email, String password) async {
    try {
      final cred = await _auth.signInWithEmailAndPassword(
          email: email, password: password);

      return AuthResult(200, user: _userFromFirebase(cred.user));
    } on auth.FirebaseAuthException catch (e) {
      print(e.toString());
      return AuthResult(0 /*<-- your error result code*/, e.toString());
    }
  }
}

最后,您的 onPressed

press: () async {

                            // SIGN IN WITH EMAIL AND PASSWORD
                            AuthResult result =
                                await auth.signInWithEmailAndPassword(
                                    email, password);

                            // IF SIGN IN FAILS
                            if (result.code != 200) {
                              setState(() {
                                errorSigningIn = result.errorMessage; //<-- Get your error message
                                //this is where I want to use the error response. 
                              });
                            }
                          },

相似文章

随机推荐

最新文章