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

Flutter Google Sign In无法获取用户姓名问题排查及解决

问题排查与解决方法

核心问题1:属性名拼写错误

你的代码里user.displayname是小写的d,而Firebase User对象的正确属性名是displayName(首字母大写D)。这个拼写错误会导致name变量始终为null,最终存入Firestore时被默认值“Guest user”替代。

核心问题2:Google登录未请求用户权限

默认的GoogleSignIn()初始化不会主动请求用户的个人资料权限,可能导致无法获取姓名信息。需要显式指定请求的权限范围。

修复后的完整代码

signInWithGoogle() async {
  // 初始化GoogleSignIn时添加profile和email权限
  final GoogleSignIn googleSignIn = GoogleSignIn(
    scopes: [
      'email',
      'profile',
    ],
  );

  final GoogleSignInAccount? googleUser = await googleSignIn.signIn();
  if (googleUser == null) return; // 用户取消登录

  final GoogleSignInAuthentication? googleAuth = await googleUser.authentication;
  var credential = GoogleAuthProvider.credential(
    accessToken: googleAuth?.accessToken,
    idToken: googleAuth?.idToken,
  );

  await FirebaseAuth.instance.signInWithCredential(credential).then((value) {
    final user = value.user!;
    // 优先从GoogleSignInAccount获取姓名(更可靠),再降级到Firebase User的displayName
    final userName = googleUser.displayName ?? user.displayName ?? 'Guest user';
    
    setState(() {
      id = user.uid; 
      name = userName;
      email = user.email ?? 'a@gmail.com';
    });

    if (value.additionalUserInfo!.isNewUser) {
      FirebaseFirestore.instance
          .collection("users")
          .doc(id)
          .set({
            'email': email, 
            'name': name,
          });
    }
  });
}

额外优化说明

  • 优先使用googleUser.displayName:因为GoogleSignInAccount直接从Google服务器获取用户信息,比Firebase Auth同步的信息更可靠,避免同步延迟或权限问题。
  • 添加空值判断:如果用户取消登录,直接终止流程,避免后续空指针异常。
  • 兜底默认值:即使所有获取渠道都失败,也显式设置“Guest user”,避免存入null。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:09:59