【问题标题】:How to store in Firestore Database after add it to firebase authentication in flutter在颤振中将其添加到firebase身份验证后如何存储在Firestore数据库中
【发布时间】:2021-09-04 18:37:08
【问题描述】:

我已经注册并登录了该应用程序,用户可以将其存储到 Firebase 身份验证中,但它没有存储到 Firestore 数据库中。这一次,我也想将其存储到 Firestore 数据库中。有人知道如何存储到 Firestore 数据库吗?请帮忙,谢谢

注册码

class _SignUpPageState extends State<SignUpPage> {
  FirebaseAuth _auth = FirebaseAuth.instance;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();


  String _username, _email, _password;

  checkAuthentication() async {
    _auth.authStateChanges().listen((user) async {
      if (user != null) {
        Navigator.pushReplacementNamed(context, "start");

      }

    });
  }

  @override
  void initState() {
    super.initState();
    this.checkAuthentication();
  }

  signUp() async {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();

      try {
        UserCredential user = await _auth.createUserWithEmailAndPassword(
            email: _email, password: _password);

        if (user != null) {
          await _auth.currentUser.updateProfile(displayName: _username);

          // await Navigator.pushReplacementNamed(context,"/") ;

        }
      } catch (e) {
        showError(e.message);
        print(e);
      }
    }
  }

  showError(String errormessage) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('ERROR'),
            content: Text(errormessage),
            actions: <Widget>[
              FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('OK'))
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.white,
        appBar: AppBar(
          elevation: 0,
          brightness: Brightness.light,
          backgroundColor: Colors.white,
          leading: IconButton(
            onPressed: (){
              //Navigator.pop(context, SignUpPage());
              Navigator.push(context, MaterialPageRoute(builder: (context) => WelcomeScreen()));
            },
            icon: Icon(Icons.arrow_back_ios,
              size: 20,
              color: Colors.black,),
          ),
        ),
        body: SingleChildScrollView(
          child: Container(
            child: Column(
              children: <Widget>[
                Container(
                  height: 300,
                  child: Image(
                    image: AssetImage("assets/girlsave.png"),
                    fit: BoxFit.contain,
                  ),
                ),
                Container(
                  child: Form(
                    key: _formKey,
                    child: Column(
                      children: <Widget>[
                        Container(
                          child: TextFormField(
                              validator: (input) {
                                if (input.isEmpty) return 'Enter Username';
                              },
                              decoration: InputDecoration(
                                labelText: 'Username',
                                labelStyle: TextStyle(color: Colors.grey),
                                prefixIcon: Icon(
                                    Icons.person,
                                    color: primary,
                                ),
                                focusedBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(color: secondary),
                                ),
                              ),
                              onSaved: (input) => _username = input),
                        ),
                        Container(
                          child: TextFormField(
                              validator: (input) {
                                if (input.isEmpty) return 'Enter Email';
                              },
                              decoration: InputDecoration(
                                  labelText: 'Email',
                                  labelStyle: TextStyle(color: Colors.grey),
                                  prefixIcon: Icon(
                                      Icons.email,
                                      color: primary,
                                  ),
                                focusedBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(color: secondary),
                                ),
                              ),
                              onSaved: (input) => _email = input),
                        ),
                        Container(
                          child: TextFormField(
                              validator: (input) {
                                if (input.length < 8)
                                  return 'Provide Minimum 8 Character';
                              },
                              decoration: InputDecoration(
                                labelText: 'Password',
                                labelStyle: TextStyle(color: Colors.grey),
                                prefixIcon: Icon(
                                    Icons.lock,
                                    color: primary,
                                  ),
                                focusedBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(color: secondary),
                                ),
                              ),
                              obscureText: true,
                              onSaved: (input) => _password = input),
                        ),
                        SizedBox(height: 20),
                        RaisedButton(
                          padding: EdgeInsets.fromLTRB(70, 10, 70, 10),
                          onPressed: signUp,
                          child: Text('Sign Up',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 20.0,
                                  fontWeight: FontWeight.bold)),
                          color: primary,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20.0),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ));
  }
}

登录代码

class _LoginPageState extends State<LoginPage> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  String _email, _password;

  checkAuthentification() async {
    _auth.authStateChanges().listen((user) {
      if (user != null) {
        print(user);

        Navigator.pushReplacementNamed(context, "start");
      }
    });
  }

  @override
  void initState() {
    super.initState();
    this.checkAuthentification();
  }

  login() async {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();

      try {
        await _auth.signInWithEmailAndPassword(
            email: _email, password: _password);
      } catch (e) {
        showError(e.message);
        print(e);
      }
    }
  }

  showError(String errormessage) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('ERROR'),
            content: Text(errormessage),
            actions: <Widget>[
              FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('OK'))
            ],
          );
        });
  }

  navigateToSignUp() async {
    Navigator.push(context, MaterialPageRoute(builder: (context) => SignUpPage()));
  }
  navigateToForgotPassword() async {
    Navigator.push(context, MaterialPageRoute(builder: (context) => ForgotPasswordPage()));
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.white,
        appBar: AppBar(
          elevation: 0,
          brightness: Brightness.light,
          backgroundColor: Colors.white,
          leading: IconButton(
            onPressed: (){
              //Navigator.pop(context,LoginPage());
              Navigator.push(context, MaterialPageRoute(builder: (context) => WelcomeScreen()));
            },
            icon: Icon(Icons.arrow_back_ios,
              size: 20,
              color: Colors.black,),
          ),
        ),
        body: SingleChildScrollView(
          child: Container(
            child: Column(
              children: <Widget>[
                Container(
                  height: 300,
                  child: Image(
                    image: AssetImage("assets/girlsave.png"),
                    fit: BoxFit.contain,
                  ),
                ),
                Container(
                  child: Form(
                    key: _formKey,
                    child: Column(
                      children: <Widget>[
                        Container(
                          child: TextFormField(
                              validator: (input) {
                                if (input.isEmpty) return 'Enter Email';
                              },
                              decoration: InputDecoration(
                                  labelText: 'Email',
                                  labelStyle: TextStyle(color: Colors.grey),
                                  prefixIcon: Icon(
                                    Icons.email,
                                    color: secondary,
                                  ),
                                focusedBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(color: secondary),
                                ),
                              ),
                              onSaved: (input) => _email = input),
                        ),
                        Container(
                          child: TextFormField(
                              validator: (input) {
                                if (input.length < 6)
                                  return 'Provide Minimum 6 Character';
                              },
                              decoration: InputDecoration(
                                labelText: 'Password',
                                labelStyle: TextStyle(color: Colors.grey),
                                prefixIcon: Icon(
                                    Icons.lock,
                                  color: secondary,
                                ),
                                focusedBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(color: secondary),
                                ),
                              ),
                              obscureText: true,
                              onSaved: (input) => _password = input),
                        ),
                        SizedBox(height: 20),
                        RaisedButton(
                          padding: EdgeInsets.fromLTRB(70, 10, 70, 10),
                          onPressed: login,
                          child: Text('LOGIN',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 20.0,
                                  fontWeight: FontWeight.bold)),
                          color: primary,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20.0),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                GestureDetector(
                  child: Text('Create an Account?'),
                  onTap: navigateToSignUp,
                ),
                GestureDetector(
                  child: Text('Forgot Password?'),
                  onTap: navigateToForgotPassword,
                ),
              ],
            ),
          ),
        ));
  }
}

【问题讨论】:

    标签: flutter google-cloud-firestore firebase-authentication


    【解决方案1】:

    首先,转到 firebase 控制台并启用项目的 Firestore Database(来自 sidemenu)。

    添加依赖cloud_firestore

    然后改进您的注册功能如下

      signUp() async {
        if (_formKey.currentState.validate()) {
          _formKey.currentState.save();
    
          try {
            UserCredential user =
                await _auth.createUserWithEmailAndPassword(email: _email, password: _password);
    
            if (user != null) {
              await _auth.currentUser.updateProfile(displayName: _username);
    
              await FirebaseFirestore.instance.collection('yourCollection').doc(user.user.uid).set({
                // Map of your data
              });
    
              // await Navigator.pushReplacementNamed(context,"/") ;
    
            }
          } catch (e) {
            showError(e.message);
            print(e);
          }
        }
      }
    

    如果您遇到权限问题,请在Rules 部分设置以下规则

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if true;
        }
      }
    }
    

    您可以根据数据库的集合和文档修改规则。这将帮助您保护您的数据。

    Here您可以了解安全规则的工作原理。

    【讨论】:

    • 嗨,感谢您的回复,所以我通过添加以下数据来映射我的数据:'uid':user.uid,'username':_username,'e​​mail':_email,'password':_password。但它显示“没有为类型 'UserCredential' 定义 getter 'uid'。”怎么修?谢谢
    • 应该是user.user.uid 而不是user.uid
    • 嗨,是的,它可以,但是当我运行它时,它仍然没有存储到 Firestore,而是存储在 Firebase 身份验证中。这是错误“ W/Firestore(30133): (23.0.1) [WriteStream]: (f41aad5) Stream closed with status: Status{code=PERMISSION_DENIED, description=The caller does not have permission, cause=null}. W /Firestore(30133): (23.0.1) [Firestore]: Write failed at users/vLZ4EJpWpPPvOHziAyCGkGFVgdT2: Status{code=PERMISSION_DENIED, description=调用者没有权限,cause=null} "
    • 您需要在 firebase.rules 中为该集合设置规则
    • 嗨,我可以知道我应该在哪里添加规则吗?如何?谢谢@blaneyneil
    猜你喜欢
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    相关资源
    最近更新 更多