用户使用Firebase注册时如何保存名称?

时间:2020-10-02 10:36:13

标签: firebase flutter dart

我正在使用Firebase构建一个应用程序,并且我想保存用户名以便稍后在配置文件页面中显示。我尝试了一些方法,但是我不知道如何正确地做,因为我是扑扑的初学者。

firebaseHelper.dart

  Future<AuthResultStatus> createAccount({email, password}) async {
try {
  AuthResult authResult = await _auth.createUserWithEmailAndPassword(
      email: email, password: password);
  if (authResult.user != null) {
    _status = AuthResultStatus.successful;
  } else {
    _status = AuthResultStatus.undefined;
  }
} catch (e) {
  print('Exception @createAccount: $e');
  _status = AuthExceptionHandler.handleException(e);
}
return _status;}

signup.dart

  createAccount() async {
final status = await FirebaseHelper().createAccount(

    email: emailInputController.text,
    password: pwdInputController.text);
if (status == AuthResultStatus.successful) {
  // Navigate to success page
  Navigator.pushAndRemoveUntil(
      context,
      MaterialPageRoute(builder: (context) => MyNavHomePage()),
      (r) => false);
} else {
  final errorMsg = AuthExceptionHandler.generateExceptionMessage(status);
  _showAlertDialog(errorMsg);
}}

如果我无意中错过了一些东西,请告诉我。预先谢谢你。

1 个答案:

答案 0 :(得分:2)

您必须将数据存储在Firestore中。

创建用户帐户时,请在一组用户中创建一个新的用户文档。将文档名称设为您使用auth创建的新用户的uid。在该文档中,您可以存储该用户的姓名和其余数据。

要获取登录用户的名称时,请获取以该用户的uid命名的文档。

Firebase身份验证仅用于登录

要存储用户数据-> firestore

示例:

final db = Firestore.instance;
FirebaseAuth auth = FirebaseAuth.instance;

//This method is used to create the user in firestore
Future<void> createUser(String uid, String username, String email, int age) async {
  //Creates the user doc named whatever the user uid is in te collection "users" 
  //and adds the user data 
  await db.collection("users").document(uid).setData({
    'Name': username,
    'Email': email,
    'Age' : age    
  });
}

//This function registers a new user with auth and then calls the function createUser
Future<void> registerUser(String email, String password, String username) async {
   //Create the user with auth
   AuthResult result = await auth.createUserWithEmailAndPassword(email: email, password: password);

   //Create the user in firestore with the user data
   createUser(result.user.uid, username, email, age);
}

//Function for logging in a user
Future<void> logIn(String email, String password) async {
     //sign in the user with auth and get the user auth info back 
     FirebaseUser user = (await auth.signInWithEmailAndPassword(email: email, password: password)).user;
     
     //Get the user doc with the uid of the user that just logged in
     DocumentReference ref = await db.collection("users").document(user.uid);
     DocumentSnapshot snapshot = await ref.get()

     //Print the user's name or do whatever you want to do with it
     print(snapshot.data["Name"]);


此代码未经100%测试。这是我执行了此功能的项目中的代码的混合。不要复制粘贴。了解它并使其适应您的需求和软件包版本。我认为没有任何改变,但我只是为了以防万一。