将其添加到flutter中的firebase身份验证后如何将其存储在Firestore数据库中

新用户

我已经注册并登录了应用程序,用户可以将其存储到 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,
                ),
              ],
            ),
          ),
        ));
  }
}
赫马尔

首先,转到 firebase 控制台并启用Firestore Database(从侧边菜单)您的项目。

添加依赖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;
    }
  }
}

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

您可以在此处了解安全规则的工作原理。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何将ASP.NET MVC5身份验证添加到现有数据库

如何在Laravel中为每个用户生成唯一的随机值并将其添加到数据库

如何将2要素身份验证添加到与googleauthr连接的闪亮应用中

Firebase将经过身份验证的用户添加到数据库

如何将图像上传到Firebase存储并将其添加到数据库?

如何将身份验证证书添加到存储库

如何将元数据添加到Firebase身份验证

Flutter Firebase将其他用户信息(例如地址)添加到数据库

如何将身份验证标头添加到axios挂钩请求中?

进行注册身份验证并将其存储在数据库中的正确方法是什么?

如何将数据添加到Firestore数据库中的现有文档

如何将新对象添加到现有实体,将数据放入数据中并让EF将其添加到我的数据库中?

将属性添加到数据存储后,如何将其添加到EntityType?

在Android上将其他经过身份验证的数据添加到AES-GCM

如何使用PHP提取API数据并将其添加到数据库中?

如何将其存储在数据库中?

动态输入并将其添加到数据库中

Firebase Web身份验证并添加到数据库

如何从数据库中获取布尔值并将其添加到 TextView?

使用 firebase (React) (Google 身份验证) 将用户数据添加到数据库

从数据库中绘制一个链接并将其添加到 HTML 中

如何将数据添加到 firebase 数据库中已有的引用?

如何检查重复输入并防止将其添加到数据库中

如何将数据添加到 Firestore 数据库子集合中的特定文档?

如何将新数据添加到 android 中的 Firebase 数据库?

将对象添加到 firebase 实时数据库列表会将其转换为 HashMap。如何将其保留为列表或转换它

如何创建命令并将其添加到 python 存储库中的路径

数据未存储在 Firestore 中,但用户的身份验证信息在 Firebase 身份验证中可用

如何将 Firebase 身份验证数据添加到 React 中的 Firestore 集合?