在 Flutter 中使用 Google Sign-In 获取用户的生日/性别 [英] Get user's birthday/gender using Google Sign-In in Flutter

查看:36
本文介绍了在 Flutter 中使用 Google Sign-In 获取用户的生日/性别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to get user's birthday and gender using Firebase Auth and Google Sign-In. Unfortunately, after the login happens, I am getting only the user's email, display name, photo url and phone number. I saw that I can add scopes to the GoogleSignIn object, which I do - https://www.googleapis.com/auth/user.birthday.read, https://www.googleapis.com/auth/userinfo.profile, but still, I don't see any additional data after the login. Any idea how to get the result of this? Because when these scopes are added to the object, it asks me if I accept to give this data before doing the login, so I guess there should be a way to fetch and display them.

这是我的登录代码:

  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;
  }

推荐答案

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

I hope this becomes useful to anyone else facing the same trouble :)

 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"];
  }

这篇关于在 Flutter 中使用 Google Sign-In 获取用户的生日/性别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆