Firebase中的displayName为空的问题在使用signInWithCredential进行登录时出现
P粉328911308
P粉328911308 2023-09-04 09:43:01
0
2
514
<p>我正在使用Google登录,提示用户输入Google账户的电子邮件和密码:</p> <pre class="brush:php;toolbar:false;">const auth = getAuth(app); const userCredentials = await signInWithCredential( auth, GoogleAuthProvider.credential(null, token) ); console.log(userCredentials.user)</pre> <p>我成功获取到用户对象,其中包括<code>email</code>、<code>photoURL</code>、<code>uid</code>等信息,但是<code>displayName</code>为空。这是一个错误还是预期结果?我尝试创建了一个新的Gmail账户,包括姓名和昵称,但是<code>displayName</code>仍然为空。我该如何获取<code>displayName</code>?</p>
P粉328911308
P粉328911308

全部回复(2)
P粉794851975

我找到了一个方法来“黑掉”关于无法从signInWithCredential获取displayName的问题。显然,正如之前所说的,displayName始终为null。但是,如果你使用google_sign_in库进行登录并检查GoogleSignInAccount对象,你将会看到你将拥有该显示名称。然后,你可以使用之前使用的Google登录凭据登录到Firebase。 以下是我使用的代码:

try {
      GoogleSignIn _googleSignIn = GoogleSignIn();
      GoogleSignInAccount? googleSignInAccount = await _googleSignIn.signIn();
      if (googleSignInAccount == null) {
        print('error getting google sign in account');
        return;
      }

      GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount!.authentication;
      AuthCredential credential = GoogleAuthProvider.credential(
          idToken: googleSignInAuthentication.idToken, accessToken: googleSignInAuthentication.accessToken);

      var result = (await _auth.signInWithCredential(credential));
      user = result.user;
      displayName = googleSignInAccount.displayName;
    } catch (e) {
      print(e);
    }

user变量中,你将拥有来自firebase身份验证的所有与用户相关的变量,例如uid,而从googleSignInAccount中你可以获取显示名称。 希望这能帮助到某人!

P粉073857911

默认情况下,UserdisplayName属性为空。它取决于用户在创建或更新时是否设置了displayName。但默认情况下它是null

如果你想在某个地方更新displayName,可以使用以下方法:updateProfile

import { getAuth, updateProfile } from "firebase/auth";
const auth = getAuth(app);
const user = auth.currentUser;

await updateProfile(user, {
  displayName: "John Doe"
});

console.log(user.displayName);

如果你确定你的Google账户中有displayName,但在user.displayName中没有显示出来,那么你需要检查你传递给GoogleAuthProvider.credential()方法的idToken是否为null,确保你也传递了有效的idToken

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!