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

时间:2018-05-16 02:52:54

标签: firebase dart firebase-authentication flutter

我正在我的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.)

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

3 个答案:

答案 0 :(得分:2)

在其后使用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!
      }
    }
}

答案 1 :(得分:1)

如果您使用的是 Visual Studio Code,请取消选中“Uncaught Exceptions”选项。这将解决您的问题。将执行 catch 块内的语句。 Please check the below image where both the options are unchecked.

答案 2 :(得分:0)

看看Dart中的Futures and error handling。您还可以使用the (\w+) filter is clicked .then处理错误。我正在致电.onError在屏幕上显示错误消息。下面的示例代码用于注册。

SetState()