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

问题描述 投票:0回答:5

我可以使用 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;
}

}

登记表按钮:

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;
      });
     }
    }
   }
firebase flutter dart firebase-authentication
5个回答
14
投票

您可以使用 FirebaseUser 类中给出的

updateProfile
方法 来更新名称和照片 url。

updateProfile({String displayName, String photoURL}).

对于电子邮件,您可以使用不同的方法

updateEmail(String newEmail)
这是一个异步方法。

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


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;
  }
}

4
投票

您可以在 updateDisplayName()

 对象上使用 
updatePhotoURL()
User
 方法将 displayName/个人资料图像添加到 Firebase 用户。

final userCredential = await _auth.createUserWithEmailAndPassword(
  email: email,
  password: password,
);

//After creating a user in Firebase, we then are able to change name/pictue
await userCredential.user?.updateDisplayName(name);

await userCredential.user?.updatePhotoURL(imageUrl);

截至 2021 年 10 月,

updateProfile()
已弃用,您应该使用
updateDisplayName()
updatePhotoURL()
代替。


0
投票
late User userFirebase;
Future<UserCredential> userCredential =await //Your code signin or signup
await userCredential.then((UserCredential value)  {
userFirebase = value.user!;
});
await userFirebase.updateDisplayName(event.name);

0
投票

如果您想更新用户名或非常简单地编辑它,您可以更新它

  final credential = FirebaseAuth.instance;

future<void> updateUserName(String name){ credential.currentUser!.updateDisplayName(name);
}
© www.soinside.com 2019 - 2024. All rights reserved.