【问题标题】:Flutter Firestore adding dataFlutter Firestore 添加数据
【发布时间】:2021-01-08 06:58:17
【问题描述】:

我想在 Firestore 上添加数据,但它不起作用。有人可以帮助我吗? 这是最新的更新版本,我不知道如何... firebase_auth: ^0.18.0+1 cloud_firestore: ^0.14.0+2

这是注册屏幕,所以我想在创建电子邮件和密码后发送数据。 我也想添加带有用户 uid 的文档。

onPressed: () async {
                  try {
                    UserCredential userCredential = await FirebaseAuth
                        .instance
                        .createUserWithEmailAndPassword(
                      email: _emailController.text,
                      password: _passwordController.text,
                    );
                    if (userCredential != null) {
                      firestore
                          .collection("user")
                          .doc('user.uid')
                          .set({
                            'username': username,
                            'email': email,
                          })
                          .then((value) => print("User Added"))
                          .catchError((error) =>
                              print("Failed to add user: $error"));
                      Navigator.of(context).pushNamed(AppRoutes.authLogin);
                    }
                  } catch (e) {
                    print(e);
                    _usernameController.text = "";
                    _passwordController.text = "";
                    _repasswordController.text = "";
                    _emailController.text = "";
                    //TODO: alertdialog with error
                  }
                  setState(() {
                    saveAttempted = true;
                  });
                  if (_formKey.currentState.validate()) {
                    _formKey.currentState.save();
                  }
                },

有人可以帮我做firestore吗..谢谢..

【问题讨论】:

  • 使用 if (_formKey.currentState.validate()) { _formKey.currentState.save(); } 来包装函数的其余部分......这样你首先保存表单,以便你可以发布它的数据
  • 要按用户 ID 存储用户文档,您需要从 firebase 获取用户信息。在那里,您将获得用户 ID。我在下面分享了综合代码

标签: firebase flutter google-cloud-firestore


【解决方案1】:

首先创建一个用户类。

  class UserData {
  final String userId;
  final String fullNames;
  final String email;
  final String phone;
  UserData(
      {this.userId,
      this.fullNames,
      this.email,
      this.phone});

  Map<String, dynamic> getDataMap() {
    return {
      "userId": userId,
      "fullNames": fullNames,
      "email": email,
      "phone": phone,
    };
  }
}

然后您可以使用类似这样的功能来保存凭据并将数据保存到 firestore

createOrUpdateUserData(Map<String, dynamic> userDataMap) async {
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
    DocumentReference ref =
        Firestore.instance.collection('user').document(user.uid);
    return ref.setData(userDataMap, merge: true);
  }

==

bool validateAndSave() {
final form = _formKey.currentState;
if (form.validate()) {
  form.save();
  return true;
}
return false;
 }  

 void validateAndSubmit() async {
        if (validateAndSave()) {
          try {
            String userId = _formType == FormType.login
               ? await widget.auth.signIn(_email, _password)//use your signin
              : await widget.auth.signUp(_email, _password);//use your signup
            if (_formType == FormType.register) {
              UserData userData = new UserData(
                fullNames: _fullNames,
                email: _email,
                phone: "",            
          );
          createOrUpdateUserData(userData.getDataMap());
        }

    } catch (e) {
    setState(() {
      _isLoading = false;
      switch (e.code) {
        case "ERROR_INVALID_EMAIL":
          _authHint = "Your email address appears to be malformed.";
          break;
        case "ERROR_EMAIL_ALREADY_IN_USE":
          _authHint = "Email address already used in a different account.";
          break;
        case "ERROR_WRONG_PASSWORD":
          _authHint = "Your password is wrong.";
          break;
        case "ERROR_USER_NOT_FOUND":
          _authHint = "User with this email doesn't exist.";
          break;
         case "EMAIL NOT VERIFIED":
          _authHint = "Email not verified: Please go to yor email and verify";
          break;
        case "ERROR_USER_DISABLED":
          _authHint = "User with this email has been disabled.";
          break;
        case "ERROR_TOO_MANY_REQUESTS":
          _authHint =
              "Too many Attemps. Account has temporarily disabled.\n Try again later.";
          break;
        case "ERROR_OPERATION_NOT_ALLOWED":
          _authHint = "Signing in with Email and Password is not enabled.";
          break;
        case "ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL":
          _authHint = "The email is in use by another account";
          break;
        default:
          _authHint = "An undefined Error happened.";
      }
    });
    print(e);
    errorDialog(context, _authHint);
  }
} else {
  setState(() {
    _authHint = '';
  });
}

}

然后使用

onpressed:(){
              validateAndSubmit();
                 }

表单类型是枚举

enum FormType { login, register, reset }

widget.auth.signIn 和 widget.auth.signUp 应分别替换为您的登录和注册。

添加了一个自定义错误块来区分 firebase 身份验证错误。

独立定义身份验证页面将有助于您将来重用代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 2020-09-07
    • 2020-08-09
    • 2021-06-23
    • 1970-01-01
    • 2021-12-26
    • 2023-03-24
    • 2021-09-16
    相关资源
    最近更新 更多