使用 firebase 和 flutter 登录谷歌后获取用户详细信息

时间:2021-06-12 20:03:01

标签: firebase flutter dart firebase-authentication google-cloud-functions

在用户在 Flutter 中使用 firebase 与 google 签约后,我正在尝试获取用户详细信息。这是我拥有的代码,它成功地让用户登录,但是当我访问详细信息时,当我将鼠标悬停在红线上时,它会给我这条消息 - 错误 - 无法无条件访问属性“用户名”,因为接收者可能为“空”

  Future<User?> signInWithGoogle() async {
    FirebaseAuth auth = FirebaseAuth.instance;
    User? user;
    final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
    if (googleUser != null) {
      final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
      final AuthCredential credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );
      try {
        final UserCredential userCredential = await auth.signInWithCredential(credential);
        final user = userCredential.additionalUserInfo.username;
        print(user);
      } on FirebaseAuthException catch (e) {
        if (e.code == 'account-exists-with-different-credential') {

        } else if (e.code == 'invalid-credential') {

        }
      } catch (e) {

      }
    }
    return user;
  }
}

这是用户变量下出现的红线截图—— enter image description here

如何获取登录用户的所有详细信息,包括会话信息?

1 个答案:

答案 0 :(得分:1)

您看到错误消息的原因很好解释:值 username 不能像那样使用,因为该值的所有者可以是 null 所以你需要检查首先是它是否为空。

使用 onAuthStateChanged 侦听器获取用户数据:

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

这将使您更轻松地进行身份验证状态管理,并为您使用的任何提供程序概括工作流程。您还可以使用它捕获注销