使用Flutter,如何在单独的登录页面小部件中显示AuthService类中捕获的Firebase Auth错误消息



我有一个注册页面和我的注册表单,然后我调用一个AuthService类来注册用户,返回一个映射的自定义user类。我可以检查函数调用的结果是否为null,因此可以将用户导航到主页,但我无法确定如何设置State或类似方法,以便在我的注册页面中向用户实际显示Firebase Auth消息,因为try/catch块在我的Auth服务类中。

这是我的缩写注册屏幕小部件:

class RegistrationScreen extends StatefulWidget {
@override
_RegistrationScreenState createState() => _RegistrationScreenState();
}
class _RegistrationScreenState extends State<RegistrationScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
//abbreviated...
RoundedButton(
onPressed: () async {
if (_formKey.currentState.validate()) {
dynamic result = await _auth.registerWithEmailAndPassword(email, password, displayName);
if (result != null) {
Navigator.pushNamedAndRemoveUntil(context, Home.id, (_) => false);
} 
}
}
}
}

registerWithEmailAndPassword位于导入的AuthService类auth.dart:中

class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
final _firestore = Firestore.instance;
//create User object
User _userFromFirebaseUser(FirebaseUser user) {
return user != null ? User(uid: user.uid, displayName: user.displayName) : null;
}
//auth change user stream
Stream<User> get user {
return _auth.onAuthStateChanged
.map(_userFromFirebaseUser);
}
// register
Future registerWithEmailAndPassword(String email, String password, String displayName) async {
try { 
AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
return _userFromFirebaseUser(user);
} catch(e) {
print(e);
} 
} 
}

如果我用一封格式不正确的电子邮件进行测试,我会正确地打印到控制台:

flutter: PlatformException(ERROR_INVALID_EMAIL, The email address is badly formatted., null)

但是,我如何在注册屏幕中使用PlatformException来设置State或类似内容,以向用户显示e.message?

谢谢。

您可以创建这样的类;

class Errors {
   static String show(String errorCode) {
     switch (errorCode) {
       case 'ERROR_EMAIL_ALREADY_IN_USE':
         return "This e-mail address is already in use, please use a different e-mail address.";
       case 'ERROR_INVALID_EMAIL':
         return "The email address is badly formatted.";
       case 'ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL':
         return "The e-mail address in your Facebook account has been registered in the system before. Please login by trying other methods with this e-mail address.";
       case 'ERROR_WRONG_PASSWORD':
         return "E-mail address or password is incorrect.";
       default:
         return "An error has occurred";
     }
   }
}

然后,当您收到PlatformException错误时,您可以向用户显示这样的警报对话框;

try { 
AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
return _userFromFirebaseUser(user);
} catch(e) {
print(Errors.show(e.code));   // On this line, call your class and show the error message.
} 

最新更新