Firebase中的displayName為空的問題在使用signInWithCredential進行登入時出現
P粉328911308
P粉328911308 2023-09-04 09:43:01
0
2
517
<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學習者快速成長!