如何在flutter中成功检测firebase用户注册和登录

时间:2021-07-01 19:15:59

标签: firebase flutter firebase-authentication

根据 FlutterFire 的 documentation,有两种不同的登录和注册方法,用于电子邮件和密码身份验证。

注册

try {
  UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
    email: "barry.allen@example.com",
    password: "SuperSecretPassword!"
  );
} on FirebaseAuthException catch (e) {
  if (e.code == 'weak-password') {
    print('The password provided is too weak.');
  } else if (e.code == 'email-already-in-use') {
    print('The account already exists for that email.');
  }
} catch (e) {
  print(e);
}

用于登录

try {
  UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(
    email: "barry.allen@example.com",
    password: "SuperSecretPassword!"
  );
} on FirebaseAuthException catch (e) {
  if (e.code == 'user-not-found') {
    print('No user found for that email.');
  } else if (e.code == 'wrong-password') {
    print('Wrong password provided for that user.');
  }
}

通过此代码,我可以通过 FirebaseAuthException 处理错误并停止一些加载进度。但是如何检测该用户成功注册并按照成功注册执行某些操作?

1 个答案:

答案 0 :(得分:0)

<块引用>

但是我如何检测该用户是否成功注册?

实际上详细说明了in the documentation section that explains您在问题中提到的代码。

特别是,对于注册,doc 表示:

<块引用>

该方法是一个两步操作;它将首先创建新的 帐户(如果它不存在且密码有效)和 然后让用户自动登录到该帐户。如果您正在侦听身份验证状态的变化,一个新事件将是 发送给您的听众

要监听身份验证状态的变化,您可以调用 FirebaseAuth 实例上的 authStateChanges() 方法,如下所示:

FirebaseAuth.instance
  .authStateChanges()
  .listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      // !!!!! Here you know the user is signed-in !!!!!
      print('User is signed in!');
    }
  });

对于登录,也是一样的。 doc 声明:

<块引用>

一旦成功,如果您正在监听身份验证的变化 状态,一个新事件将发送给您的听众。

参考上面的注册案例。


因此,总而言之,一方面您调用方法来注册(createUserWithEmailAndPassword())或登录(signInWithEmailAndPassword()),另一方面,您设置一个侦听器身份验证状态的变化。当对两种方法之一的调用成功时,侦听器会提醒您。

on FirebaseAuthException catch (e) {...} 块处理对两种方法之一的调用不成功的情况。


最后,请注意 Firebase Developers Medium 出版物中的以下 article:它提供了一种略有不同的方法,声明了 async 方法来检查 user方法返回的对象是否为null,并相应地调用setState()

例如:

void _register() async {
  final FirebaseUser user = (await 
      _auth.createUserWithEmailAndPassword(
        email: _emailController.text,
        password: _passwordController.text,
      )
  ).user;
  if (user != null) {
    setState(() {
      _success = true;
      _userEmail = user.email;
    });
  } else {
    setState(() {
      _success = true;
    });
  }
}