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
(从 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;
}
}
}
您可以根据数据库的集合和文档修改规则。这将帮助您保护您的数据。
在这里,您可以了解安全规则的工作原理。
推荐阅读
- android - Android BottomNavigationView 在被删除/隐藏后留下空白
- sql - 在.net core 3.0 中是否为使用 Azure Key Vault 始终加密的 SQL 提供了适当的支持?
- linux - 如何模拟挂起的文件系统?
- c# - 如何在 C# 中将数据从指针复制到指针?
- javascript - SVG 图表 - 我如何调整 svg 的高度,以便所有标签自动适合里面
- regex - 有效 WKT 线串的正则表达式(在 BigQuery 中)?
- asp.net - Visual Studio 2019 占用大量 CPU 并非常缓慢地为简单的 asp.net 提供服务
- java - 如何针对数据库数据验证 Jmeter JSON 响应
- mysql - mysql phpmyadmin 中的存储过程 #1064
- python - 我无法在更大的字符串中找到我的子字符串