我有一个使用firestore数据库进行登录的应用程序,并且我想进行自动登录,因此我在数据库中进行了 bool(boolean) 设置并将其设置为false,并在登录时将登录功能设置为true,所以我想在应用运行时检查用户是否已经登录,是否有任何想法:)?
这是我的代码:
void getUserData() async {
try {
var firebaseUser = await FirebaseAuth.instance.currentUser();
firestoreInstance
.collection("Students")
.document(usernameController.text)
.get()
.then((value) {
setState(() {
email = (value.data)['email'];
password = (value.data)['password'];
gender = (value.data)['gender'];
loggedin = (value.data)['token'];
});
});
} catch (e) {
print(e.toString);
}
}
最佳答案
您不必使用 bool(boolean) 值来检查用户是否已登录。 Firebase身份验证已提供了这一功能。您可以在initState
内部检查:
@override
void initState() {
super.initState();
FirebaseAuth.instance.currentUser().then((res) {
print(res);
if (res != null) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => Home(uid: res.uid)),
);
}
else
{
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SignUp()),
);
}
});
}
检查是否有当前用户,然后导航到所需页面。如果您有不同类型的用户,则必须在数据库中标识它们。因此,请在Firebase身份验证中进行身份验证,并在数据库中使用
userType
字段: void registerToFb() {
firebaseAuth
.createUserWithEmailAndPassword(
email: emailController.text, password: passwordController.text)
.then((result) {
firestoreInstance.collection("users").document(result.user.uid).setData({
"email": emailController.text,
"name": nameController.text,
"userType" : "Students"
}).then((res) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => Home(uid: result.user.uid)),
);
});
}).catchError((err) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Error"),
content: Text(err.message),
actions: [
FlatButton(
child: Text("Ok"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
});
}
关于firebase - 如何调用功能ASA应用程序在运行中运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62527950/