如何在登录时检查用户并将其发送到不同的主页



我目前正在开发一个与Firebase项目的Flutter应用程序。这是我第一次尝试flutter,我面临的问题是根据用户的类型将用户发送到不同的主页。例如,一个admin用户将被发送到admin主页,一个customer用户将被发送到customer主页,等等。

我目前的登录代码确实允许我登录用户,但它们都被发送到客户的主页,因为我真的不知道如何实现一种方法来检查登录时用户的类型。我通过不同的集合和唯一的id来区分云存储中的用户;'uid'代表用户,'aid'代表机构。

我想我可以使用这个代码,但我不知道如何将它与我的登录代码放在一起:

Future<String> checkBothUserBasesForTheUser(String uid) async {
DocumentSnapshot _userDoc =
await FirebaseFirestore.instance.collection('users').doc(uid).get();
if (_userDoc.exists) return 'users';
DocumentSnapshot _agencyDoc =
await FirebaseFirestore.instance.collection('agencies').doc(uid).get();
if (_agencyDoc.exists)
return 'agencies';
else
return 'null';
}

当前登录代码:

final loginButton = Material(
elevation: 5,
borderRadius: BorderRadius.circular(30),
color: Color(0xFF003893),
child: MaterialButton(
padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
minWidth: 300,
onPressed: () {
signIn(emailController.text, passwordController.text);
},
child: Text(
"Login",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
)),
);

void signIn(String email, String password) async {
if (_formKey.currentState!.validate()) {
await _auth
.signInWithEmailAndPassword(email: email, password: password)
.then((_userDoc) => {
Fluttertoast.showToast(
timeInSecForIosWeb: 2,
gravity: ToastGravity.CENTER,
msg: "Login Successful"),
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => UserMainpage())),
})
.catchError((e) {
Fluttertoast.showToast(
timeInSecForIosWeb: 3,
gravity: ToastGravity.CENTER,
msg: "The email or password is invalid. Please check and try again.",
);
});
}
}

是否有其他方法可以在登录时检查用户类型并将其发送到各自的主页?

signInWithEmailAndPassword方法返回一个UserCredential结构,其中包含一个User类型。这个User类型似乎包含一个名为uid的属性,您可以将其传递给checkBothUserBasesForTheUser函数以检查它是哪种用户。

编辑:

然后,我认为你应该调用你的方法像checkBothUserBasesForTheUser(_userDoc.User.uid)和基于返回值重定向到一个页面或另一个。

我没有办法测试这段代码,但像这样的东西应该给你一个想法(也注意可能有一些语法错误):

void signIn(String email, String password) async {
if (_formKey.currentState!.validate()) {
await _auth
.signInWithEmailAndPassword(email: email, password: password)
.then((_userDoc) => {
checkBothUserBasesForTheUser(_userDoc.User.uid)
.then((result) => {
if(result == "users"){
Fluttertoast.showToast(
timeInSecForIosWeb: 2,
gravity: ToastGravity.CENTER,
msg: "Login Successful"),
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => UserMainpage())),
}
else(result == "agency"){
Fluttertoast.showToast(
timeInSecForIosWeb: 2,
gravity: ToastGravity.CENTER,
msg: "Login Successful"),
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => AgencyMainpage())),
}
})
})
.catchError((e) {
Fluttertoast.showToast(
timeInSecForIosWeb: 3,
gravity: ToastGravity.CENTER,
msg: "The email or password is invalid. Please check and try again.",
);
});
}
}

相关内容

最新更新