登录firebase帐户失败会引发异常并停止播放应用程序

我正在我的flutter应用程序中实现电子邮件和密码登录表单,但是当我无法登录时(例如格式错误的电子邮件或错误的密码),应用程序抛出平台异常并且模拟器停止响应 .

这是我的句柄登录功能:

Future<FirebaseUser> _handleLogin(String email, String password) async {
    print(email);
    print(password);
    print(_firebaseUser);
    try {
      FirebaseUser user = await _firebaseAuth.signInWithEmailAndPassword(
          email: email, password: password);
      print("done logging in");
      print(user.uid);
      setState(() {
        _firebaseUser = user;
      });
      print("new user set");
      return user;
    } catch (err) {
      print(err.toString());
      return null;
    }
}

即使我使用了错误的密码,错误也永远不会打印到控制台 . 而VS代码打开message_codecs.dart并给我一个错误消息 .

当我使用错误的密码登录时,这是错误消息:

Exception has occurred.
PlatformException(Error 17009, FIRAuthErrorDomain, The password is invalid or the user does not have a password.)

我是以错误的方式进行错误处理吗?如何在错误的密码或格式错误的电子邮件输入后捕获错误并使应用继续?

回答(1)

2 years ago

之后使用 finally .

Future<FirebaseUser> _handleLogin(String email, String password) async {
    print(email);
    print(password);
    print(_firebaseUser);
    FirebaseUser user;
    try {
      user = await _firebaseAuth.signInWithEmailAndPassword(
          email: email, password: password);
      print("done logging in");
      print(user.uid);

      print("new user set");
      return user;
    } catch (err) {
      print(err.toString());
    }
      finally {
       if(user != null) {
         //Log in was successfull! 
         setState(() {
          _firebaseUser = user;
        });

      }
      else {
         //Log in was unsuccessfull!
      }
    }
}