You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中通过signInWithGoogle如何获取性别、手机号及生日?

在Flutter的Google登录中获取性别、手机号和生日信息

你当前的代码完成了Google登录和Firebase认证流程,但Firebase Auth返回的UserCredential不会直接包含性别、手机号这类敏感信息——需要用登录后拿到的accessToken调用Google People API来获取这些数据。

步骤1:添加依赖

首先在pubspec.yaml中添加http包,用于发起网络请求:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0
  google_sign_in: ^5.4.0
  firebase_auth: ^4.12.0

执行flutter pub get安装依赖。

步骤2:修改登录方法,调用People API

更新你的signInWithGoogle方法,在获取到googleAuth后,用accessToken请求Google People API,解析返回的用户信息:

import 'package:http/http.dart' as http;
import 'dart:convert';

Future<UserCredential> signInWithGoogle() async {
  // 1. 发起Google登录,请求所需权限
  final GoogleSignInAccount? googleUser = await GoogleSignIn(scopes: [
    'email',
    "https://www.googleapis.com/auth/userinfo.profile",
    "https://www.googleapis.com/auth/user.phonenumbers.read",
    "https://www.googleapis.com/auth/user.birthday.read",
    "https://www.googleapis.com/auth/profile.agerange.read"
  ]).signIn();

  if (googleUser == null) {
    // 用户取消登录
    throw Exception('用户取消登录');
  }

  // 2. 获取登录凭证
  final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
  final String? accessToken = googleAuth.accessToken;

  if (accessToken == null) {
    throw Exception('无法获取accessToken');
  }

  // 3. 调用Google People API获取用户额外信息
  final userInfoResponse = await http.get(
    Uri.parse('https://people.googleapis.com/v1/people/me?personFields=birthdays,genders,phoneNumbers'),
    headers: {'Authorization': 'Bearer $accessToken'},
  );

  if (userInfoResponse.statusCode != 200) {
    throw Exception('获取用户信息失败:${userInfoResponse.body}');
  }

  final userInfo = json.decode(userInfoResponse.body);

  // 解析性别
  final gender = userInfo['genders']?.isNotEmpty == true 
      ? userInfo['genders'][0]['value'] 
      : null;

  // 解析生日(注意可能有多种格式,这里取第一个)
  final birthday = userInfo['birthdays']?.isNotEmpty == true 
      ? userInfo['birthdays'][0]['date'] 
      : null;

  // 解析手机号(取第一个有效号码)
  final phoneNumber = userInfo['phoneNumbers']?.isNotEmpty == true 
      ? userInfo['phoneNumbers'][0]['value'] 
      : null;

  // 打印获取到的信息(可根据业务需求存储或使用)
  print('性别:$gender');
  print('生日:$birthday');
  print('手机号:$phoneNumber');

  // 4. 完成Firebase认证
  final credential = GoogleAuthProvider.credential(
    accessToken: accessToken,
    idToken: googleAuth.idToken,
  );

  return await FirebaseAuth.instance.signInWithCredential(credential);
}

关键说明:

  • People API端点:使用https://people.googleapis.com/v1/people/me获取当前登录用户的信息,通过personFields参数指定需要返回的字段(比如birthdays,genders,phoneNumbers),避免返回不必要的数据。
  • 字段解析:返回的JSON中,genders、birthdays、phoneNumbers都是数组(用户可能有多个条目),这里默认取第一个有效条目。
  • 权限验证:确保你在Google Cloud Console中已经启用了People API,否则请求会失败。

内容的提问来源于stack exchange,提问作者user19068285

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 22:45:15