简体   繁体   English

Flutter Firestore 添加数据

[英]Flutter Firestore adding data

I want to add data on firestore and it wont work.我想在 firestore 上添加数据,但它不起作用。 can somebody help me.有人可以帮帮我吗This is the newest updated version and I can't figure out how... firebase_auth: ^0.18.0+1 cloud_firestore: ^0.14.0+2这是最新的更新版本,我不知道如何... firebase_auth: ^0.18.0+1 cloud_firestore: ^0.14.0+2

This is the sign up screen so I want to send data after I create the email and password.这是注册屏幕,所以我想在创建 email 和密码后发送数据。 I want to add the document with user uid too.我也想添加带有用户 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();
                  }
                },

Can someone help me with the firestore.. Thank you..有人可以帮我用 firestore 吗..谢谢..

First Create a User class.首先创建用户class。

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

Then you can use a function like this one to save the credentials and save the data to firestore然后你可以使用像这样的 function 来保存凭据并将数据保存到 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 = '';
  });
}

} }

Then use然后使用

onpressed:(){
              validateAndSubmit();
                 }

the formtype is an Enum表单类型是一个枚举

enum FormType { login, register, reset }

widget.auth.signIn and widget.auth.signUp should be replaced with your signin and signup respectively. widget.auth.signIn 和 widget.auth.signUp 应该分别替换为您的登录和注册。

Added a custom error block to differentiate firebase auth errors as well.添加了自定义错误块以区分 firebase 身份验证错误。

Defining an auth page independently will help you reuse your code in future.独立定义一个授权页面将帮助您在未来重用您的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM