Reputation: 1
My Firbase I'm developing an app with flutter. The app should use different pages for different kinds of users. There are 4 kinds of user: "Admin", "Staff", "Member", "Collector". The problem is, that I'm not able to get to the different pages and always stay on what role I put. I'm new on this flutter and dart so I need someone to help me for my capstone project. Thank you!
Here's my code for 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();
}
},
),
);
}
}
Here's my code for 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);
}
Here's my code for 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,
});
}
If you need more information about my code you can comment here. I really need help, Thank you very much!!!
Upvotes: 0
Views: 105
Reputation: 1
It will be easier if you Try to use roll based login system logic inside the signIn() method Here is an example :
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()),
);
}
}
Upvotes: 0