我正在开发一个带有 flutter 的应用程序。应用程序应该为不同类型的用户使用不同的页面。有4种用户:“管理员”、“职员”、“会员”、“收藏家”。问题是,我无法访问不同的页面并始终停留在我所扮演的角色上。我对 flutter 和 dart 很陌生,所以我需要有人帮助我完成我的顶点项目。谢谢!
这是我的 main.dart 代码
class MainPage extends StatelessWidget {
const MainPage({Key? key}) : super(key: key);
Future<String> getRole(String uid) async {
String role = "admin";
try {
final snapshot = await FirebaseFirestore.instance
.collection('users')
.doc(uid)
.get();
if (snapshot.exists) {
role = snapshot.get('role').toString();
} else {
print('Document does not exist in the database');
}
} catch (e) {
print(e);
}
return role;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return const Center(child: Text('Something Went Wrong!'));
} else if (snapshot.hasData) {
// User is authenticated, check their role
final users = snapshot.data!;
return FutureBuilder<String>(
future: getRole(users.uid),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return const Center(child: Text('Something Went Wrong!'));
} else {
final String? role = snapshot.data;
if (role == "admin") {
return const AdminPage();
} else if (role == "staff") {
return const StaffPage();
} else if (role == "member") {
return const MemberPage();
} else if (role == "collector") {
return const CollectorPage();
} else {
// Unknown role, handle accordingly
return const SigninPage();
}
}
},
);
} else {
// User is not authenticated, show sign-in page
return const SigninPage();
}
},
),
);
}
}
这是我的登录页面代码:
Future signIn() async{
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => const Center(child: CircularProgressIndicator()),
);
try {
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: emailController.text.trim(),
password: passwordController.text.trim(),
);
} on FirebaseAuthException catch (e) {
print(e);
Utils.showSnackBar(e.message);
}
Navigator.of(context).popUntil((route) => route.isFirst);
}
这是我的signUpPage代码:
Future signUp() async{
final isValid = formKey.currentState!.validate();
if (!isValid) return;
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => const Center(child: CircularProgressIndicator()));
try{
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: emailController.text.trim(),
password: passwordController.text.trim(),
);
//Display User to FireStore
addUserDetailes(
firstnameController.text.trim(),
middlenameController.text.trim(),
lastnameController.text.trim(),
fulladdressController.text.trim(),
civilstatuscontroller.text.trim(),
emailController.text.trim(),
int.parse(phonenoController.text.trim()),
int.parse(ageController.text.trim()),
);
}on FirebaseAuthException catch (e){
print(e);
Utils.showSnackBar(e.message);
}
//Navigator.of(context) not working!
navigatorKey.currentState!.popUntil((route) =>route.isFirst);
}
//display to database
Future addUserDetailes(String firstName, String middleName, String lastName, String fullAddress, String civilStatus, String email, int phoneNumber, int age ) async{
await FirebaseFirestore.instance.collection('users').add({
'first name': firstName,
'middle name': middleName,
'last name': lastName,
'full address': fullAddress,
'civil status' : civilStatus,
'email': email,
'phone number': phoneNumber,
'age' : age,
});
}
如果您需要有关我的代码的更多信息,您可以在这里发表评论。我真的需要帮助,非常感谢!!!
如果您尝试在signIn()方法中使用基于滚动的登录系统逻辑,会更容易 这是一个例子:
class _LoginExampleState extends State<LoginExample> {
TextEditingController emailController = TextEditingController();
TextEditingController _passController = TextEditingController();
signIn()async{
try{
UserCredential userCredential=await FirebaseAuth.instance
.signInWithEmailAndPassword(
email: emailController.text,
password: _passController.text,
);
var docSnapshot=userCredential.user!.uid;
var snapshot=await FirebaseFirestore.instance.collection('usersData')
.doc(docSnapshot).get();
var userData=snapshot.data();
var role =userData?['role'];
print(role.toString());
if(role=='admin'){
Navigator.push(context, MaterialPageRoute(builder: (context)=>AdminExample()));
}
if(role=='user'){
Navigator.push(context, MaterialPageRoute(builder: (context)=>UserExample()));
}
}catch(e){
return Center(
child: Text(e.toString()),
);
}
}