是否有办法在Flutter的小部件中使用catch块的结果?



我正在构建一个flutter应用程序与Firebase作为后端。我在一个单独的文件中创建了一个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变量。

我是新手,请帮忙。

谢谢。

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

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

最新更新