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

Flutter:如何通过Firebase谷歌登录获取用户出生日期(Android/iOS)

解决方案

核心原因

Firebase Auth返回的标准用户字段仅包含基础身份信息,默认不会同步谷歌账号的出生日期数据;同时你当前的谷歌登录没有申请读取用户生日的授权权限,所以无法获取对应数据。

具体实现步骤

  • 第一步:在谷歌云控制台对应项目中开启People API,否则后续接口请求会报错。
  • 第二步:修改GoogleSignIn初始化配置,新增生日读取权限的授权范围:
final GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: [
    'email',
    'https://www.googleapis.com/auth/user.birthday.read',
  ],
);
  • 第三步:拿到谷歌登录的accessToken后,调用谷歌People API接口获取生日数据,Firebase本身不会返回该字段,需要单独请求:
    你可以在获取到googleSignInAuthentication之后新增以下逻辑(需要提前导入http和dart:convert依赖):
// 新增请求生日的逻辑
final birthdayResponse = await http.get(
  Uri.parse('https://people.googleapis.com/v1/people/me?personFields=birthdays'),
  headers: {
    'Authorization': 'Bearer ${googleSignInAuthentication.accessToken}',
  },
);

if (birthdayResponse.statusCode == 200) {
  final userData = jsonDecode(birthdayResponse.body);
  if (userData['birthdays'] != null && userData['birthdays'].isNotEmpty) {
    // 取第一条公开的生日数据
    final birthdayDate = userData['birthdays'][0]['date'];
    int birthYear = birthdayDate['year'];
    int birthMonth = birthdayDate['month'];
    int birthDay = birthdayDate['day'];
    // 可在此处将生日数据存入本地存储、你的后端或Firestore
  } else {
    // 用户未公开生日,可自行添加引导用户手动填写的逻辑
  }
}

注意事项

  • 若用户的谷歌账号未设置生日,或设置了仅自己可见,即便申请了权限也无法获取到数据,需要做兜底兼容逻辑。
  • 出生日期不会自动同步到Firebase Auth的用户对象中,你需要自行存储到业务数据库中使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:36:02