firebase - 如何在登录期间检查用户并将其发送到不同的主页
问题描述
我目前正在为 Firebase 项目开发 Flutter 应用程序。这是我第一次尝试 Flutter,我遇到了根据用户类型将用户发送到不同主页的问题。例如,管理员用户将被发送到管理员主页,客户用户将被发送到客户主页等。
我当前的登录代码确实允许我登录用户,但他们都被发送到客户的主页,因为我真的不知道如何实现在登录期间检查用户类型的方法。我通过不同的集合和唯一的 id 来区分 Cloud Firestore 中的用户;用户的“uid”和代理商的“援助”。
我想我可以使用此代码,但我不知道如何将它与我的登录代码放在一起:
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方法返回一个包含User类型的UserCredential结构。此 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.",
);
});
}
}