如何将 displayName 添加到 Firebase 用户?(颤振/飞镖)

Jak*_*kob 4 dart firebase firebase-authentication flutter

我可以使用 Firebase 身份验证保存电子邮件和密码。我还使用 Cloud Firestore 保存了这些信息。但是如何在注册后添加和保存displayName呢?

我的代码:

Future registerWithEmailAndPassword(String email, String password) async {
try {
  AuthResult result = await _auth.createUserWithEmailAndPassword(
      email: email, password: password);
  FirebaseUser user = result.user;

  // create a new document for the user with the uid
  await DatabaseService(uid: user.uid)
      .updateUserData('User', user.email, 'test.de/test.png', user.uid);
  return _userFromFirebaseUser(user);
} catch (e) {
  print(e.toString());
  return null;
}
Run Code Online (Sandbox Code Playgroud)

}

注册表单按钮:

onPressed: () async {
  if (_formKey.currentState.validate()) {
    setState(() => loading = true);
    dynamic result = await _auth
        .registerWithEmailAndPassword(
            email, password);
    if (result == null) {
      setState(() {
        error = 'Valid email, please';
        loading = false;
      });
     }
    }
   }
Run Code Online (Sandbox Code Playgroud)

Nuq*_*uqo 10

如果您想将用户名以及电子邮件和密码保存在一起,请使用以下代码

final FirebaseAuth _auth = FirebaseAuth.instance; 

//register with email & password & save username instantly
Future registerWithEmailAndPassword(String name, String password, String email) async {
  try {
    UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
    User user = result.user;
    user.updateProfile(displayName: name); //added this line
    return _user(user);
  } catch(e) {
    print(e.toString());
    return null;
  }
}
Run Code Online (Sandbox Code Playgroud)


pra*_*996 7

您可以使用FirebaseUser 类中提供的updateProfile方法来更新名称和照片网址。

updateProfile({String displayName, String photoURL}).
Run Code Online (Sandbox Code Playgroud)

对于电子邮件,您可以使用不同的方法 updateEmail(String newEmail),即异步方法。

或者直接将用户名保存到 firestore 中,成功登录后,您可以使用 FirebaseFirestore 的“set”方法来保存电子邮件、密码和用户名。

  • 自 2021 年 10 月起,“updateProfile()”已被弃用,而“updateDisplayName()”可用于此目的。 (5认同)