Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user's birthday/gender using Google Sign-In in Flutter

Tags:

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.

Here is my login code:

  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;
  }
like image 842
scourGINHO Avatar asked Jan 21 '20 15:01

scourGINHO


1 Answers

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

like image 69
sabah mohd Avatar answered Oct 02 '22 16:10

sabah mohd