在 Flutter 中使用 Google Sign-In 获取用户的生日/性别

2024-02-14

我想使用 Firebase Auth 和 Google Sign-In 获取用户的生日和性别。不幸的是,登录后,我只收到用户的电子邮件、显示名称、照片网址和电话号码。我看到我可以将范围添加到 GoogleSignIn 对象,我这样做了 -https://www.googleapis.com/auth/user.birthday.read https://www.googleapis.com/auth/user.birthday.read, https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.profile,但是登录后我仍然看不到任何其他数据。知道如何得到这个结果吗?因为当这些范围添加到对象时,它会询问我是否接受在登录之前提供这些数据,所以我想应该有一种方法来获取和显示它们。

这是我的登录代码:

  final GoogleSignIn _googleSignIn = GoogleSignIn(scopes: ["email", "https://www.googleapis.com/auth/user.birthday.read", "https://www.googleapis.com/auth/userinfo.profile"]);
  final FirebaseAuth _auth = FirebaseAuth.instance;

  Future<FirebaseUser> _handleSignIn() async {
    final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
    final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    final FirebaseUser user = (await _auth.signInWithCredential(credential)).user;
    return user;
  }

我希望这对面临同样问题的其他人有用:)

 GoogleSignIn googleSignIn = GoogleSignIn(scopes: ['email',"https://www.googleapis.com/auth/userinfo.profile"]);
  
  @override
  Future<User> login() async {
    await googleSignIn.signIn();
    User user = new User(
      email: googleSignIn.currentUser.email,
      name: googleSignIn.currentUser.displayName,
      profilePicURL: googleSignIn.currentUser.photoUrl,
      gender: await getGender()
    );
     
    return user;
  }

  Future<String> getGender() async {
    final headers = await googleSignIn.currentUser.authHeaders;
    final r = await http.get("https://people.googleapis.com/v1/people/me?personFields=genders&key=",
      headers: {
        "Authorization": headers["Authorization"]
      }
    );
    final response = JSON.jsonDecode(r.body);
    return response["genders"][0]["formattedValue"];
  }

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Flutter 中使用 Google Sign-In 获取用户的生日/性别 的相关文章

随机推荐