Search code examples
flutterfirebasegoogle-cloud-platformfirebase-authenticationgoogle-signin

How to get user information such as phone number,birthdate and gender from firebase sign in?


I'm trying to get user information such as phone number, birthdate, and gender from Firebase, the request is successful but the phone number and other information are null, here is the full code:

ElevatedButton(
    onPressed: () async {

      final GoogleSignInAccount? gUser =
          await GoogleSignIn(scopes: [
        'https://www.googleapis.com/auth/user.birthday.read',
        'https://www.googleapis.com/auth/user.gender.read',
        'https://www.googleapis.com/auth/user.phonenumbers.read',
      ]).signIn();

      try {
        final gAuth = await gUser!.authentication;

        final credential = GoogleAuthProvider.credential(
            idToken: gAuth.idToken, accessToken: gAuth.accessToken);

        final UserCredential user = await FirebaseAuth.instance
            .signInWithCredential(credential);

        print(user.additionalUserInfo.toString());
        print(user.user.toString());
        print(user.credential.toString());

      } catch (v) {
        print(v);
      }

      GoogleSignIn().signOut();
    },
    child: const Text('Auth'))

I've tried the above code and got this output:

AdditionalUserInfo(isNewUser: false, profile: {given_name: ali, locale: en, family_name: ahmadi, picture: https://lh3.googleusercontent.com/a/asfdgdhgfhfjjfIO5gu-18L1NhsmTMuzasrBJUwW=s96-c, id: 11111111111, name: ali ahmadi, email: [email protected], verified_email: true, granted_scopes: https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/user.birthday.read https://www.googleapis.com/auth/user.gender.read https://www.googleapis.com/auth/user.phonenumbers.read openid https://www.googleapis.com/auth/userinfo.profile}, providerId: google.com, username: null)

I/flutter ( 9988): User(displayName: ali ahmadi, email: [email protected], emailVerified: true, isAnonymous: false, metadata: UserMetadata(creationTime: 2023-06-26 05:48:20.487Z, lastSignInTime: 2023-06-26 06:34:03.794Z), phoneNumber: null, photoURL: https://lh3.googleusercontent.com/a/hgghdfgsdfdsrOcIvngdgfdgu-gsdfgsdfsMuzasrBJUwW=s96-c, providerData, [UserInfo(displayName: ali ahmadi, email: [email protected], phoneNumber: null, photoURL: https://lh3.googleusercontent.com/a/dfdsfgasfgfdhgsIO5gu-18LgsdfsdfsdMuzasrBJUwW=s96-c, providerId: google.com, uid: 1111111111111)], refreshToken: , tenantId: null, uid: fsdfsdfghsdfsdfhdfhdfEi2)


Solution

  • When you sign in to Firebase using Google provider, the only fields inside the User object that are populated are the uid, the displayName, the email and the photoURL. On the other hand, the phoneNumber remains null because Google doesn't publically expose the phone number of the user. Besides that, as you can see in the class, there are no fields for the birthday and gender. If you need such information, you have to ask the user to provide it. This means that you have to store this information somehow, so you can later use it in your application. For that, I recommend you use Cloud Firestore or the Realtime Database.


    According to your comment, I can say that those fields are related to the Google APIs, not to a Firebase user account. So if you need to use them, the following code (not tested) might do the trick:

     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()
          //Other fields if needed
        );
         
        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"];
      }