import 'dart:async';
import 'package:auth_buttons/auth_buttons.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_application_1/Project/Admin/HomeAdmin.dart';
import 'package:flutter_application_1/Project/LoginPage/forgetpassword.dart';
import 'package:flutter_application_1/Project/LoginPage/register.dart';
import 'package:flutter_application_1/Project/NavigationBar.dart';
import '../utils/colors.dart';
bool _obscureText = true;
bool isLoading = false;
class LoginProject extends StatefulWidget {
const LoginProject({super.key});
@override
_LoginProjectState createState() => _LoginProjectState();
}
class _LoginProjectState extends State<LoginProject> {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
late String _email, _password;
Future<void> signIn() async {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return const Center(
child: CircularProgressIndicator(
color: kGreenColor,
backgroundColor: Colors.blueGrey,
),
);
});
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
setState(() {
isLoading = true;
});
try {
final UserCredential userCredential = await _auth
.signInWithEmailAndPassword(email: _email, password: _password);
final DocumentSnapshot userDoc = await FirebaseFirestore.instance
.collection('users')
.doc(userCredential.user!.uid)
.get();
final role = userDoc.get('role');
// Navigate to appropriate screen
if (role == 'user') {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => const MyBottomNavigationBar(getIndex: 0)),
);
} else if (role == 'admin') {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => const HomeAdmin()),
);
} else {
throw Exception('Invalid user role');
}
} on FirebaseAuthException catch (e) {
String errorMessage =
'An error occurred, please check your email and password';
if (e.code == 'user-not-found') {
errorMessage = 'No user found for that email.';
} else if (e.code == 'wrong-password') {
errorMessage = 'Wrong password provided for that user.';
}
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(errorMessage),
duration: const Duration(seconds: 3),
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('An unexpected error occurred.'),
duration: Duration(seconds: 3),
),
);
}
} finally {
if (mounted) {
setState(() {
isLoading = false;
});
Navigator.pop(context);
}
}
} else {
Navigator.pop(context);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
scrollDirection: Axis.vertical,
children: [
Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const SizedBox(
height: 13,
),
const Text(
'Welcome Back!',
style: TextStyle(
color: kPrimaryColor,
fontSize: 50,
height: 1,
fontWeight: FontWeight.bold),
),
RichText(
text: const TextSpan(
text:
'Enter your Email address and password to sign in.\nEnjoy your borrowing :)',
style: TextStyle(
height: 1.4,
color: Color(0xff868686),
fontSize: 13,
fontWeight: FontWeight.w400,
),
),
),
const SizedBox(
height: 20,
),
TextFormField(
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter an email address';
} else if (!RegExp(r"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$")
.hasMatch(value)) {
return 'Please enter a valid email address';
}
return null;
},
onSaved: (input) => _email = input!.trim(),
decoration: InputDecoration(
isDense: true,
filled: true,
fillColor: const Color.fromARGB(246, 246, 246, 246),
contentPadding: const EdgeInsets.fromLTRB(14, 18, 14, 10),
labelText: 'Email Address',
labelStyle: const TextStyle(fontSize: 14),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: const BorderSide(
color: Color.fromARGB(232, 232, 232, 232),
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
),
),
),
const SizedBox(
height: 10,
),
TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
}
if (value.length < 8) {
return 'Password must be at least 8 characters long';
}
return null;
},
onSaved: (input) => _password = input!,
decoration: InputDecoration(
isDense: true,
filled: true,
fillColor: const Color.fromARGB(246, 246, 246, 246),
contentPadding: const EdgeInsets.fromLTRB(14, 18, 14, 10),
labelText: 'Password',
labelStyle: const TextStyle(fontSize: 14),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
borderSide: const BorderSide(
color: Color.fromARGB(232, 232, 232, 232),
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
),
suffixIcon: IconButton(
icon: Icon(
_obscureText
? Icons.visibility
: Icons.visibility_off,
color: Colors.grey,
),
onPressed: () {
setState(() {
_obscureText = !_obscureText;
});
},
),
),
obscureText: _obscureText,
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ForgetPassword()),
);
},
child: Center(
child: RichText(
text: const TextSpan(
style: TextStyle(
height: 1.3,
color: Color(0xff868686),
fontSize: 13,
fontWeight: FontWeight.w400,
),
children: <TextSpan>[
TextSpan(
text: 'Forget Password?',
style: TextStyle(
color: Color(0xff868686),
fontWeight: FontWeight.w400,
),
),
],
),
),
),
),
],
),
const SizedBox(height: 10),
Center(
child: ElevatedButton(
onPressed: signIn,
style: ElevatedButton.styleFrom(
backgroundColor: kGreenColor,
foregroundColor: kWhiteColor,
padding: const EdgeInsets.all(13),
minimumSize: const Size(350, 10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
child: const Text(
'SIGN IN',
),
),
),
const SizedBox(height: 15),
Center(
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SignupProject()),
);
},
child: RichText(
text: const TextSpan(
text: 'Don\'t have an account?\t ',
style: TextStyle(
height: 1.3,
color: Color(0xff868686),
fontSize: 13,
fontWeight: FontWeight.w400,
),
children: <TextSpan>[
TextSpan(
text: 'Create new Account',
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.w400,
),
),
],
),
textAlign: TextAlign.center,
),
),
),
// const SizedBox(height: 10),
// const Center(
// child: Text(
// 'Or',
// style: TextStyle(
// height: 1.3,
// color: Color(0xff868686),
// fontSize: 17,
// fontWeight: FontWeight.bold,
// ),
// ),
// ),
// const SizedBox(height: 10),
// Center(
// child: GoogleAuthButton(
// onPressed: () {
// // your implementation
// setState(() {
// isLoading = !isLoading;
// });
// },
// isLoading: isLoading,
// style: AuthButtonStyle(
// buttonColor: Colors.lightBlue[400],
// textStyle: const TextStyle(
// fontSize: 16,
// color: Colors.white,
// fontWeight: FontWeight.bold),
// width: 350.0,
// height: 45.0,
// separator: 10.0),
// ),
// ),
// const SizedBox(height: 10),
// Center(
// child: FacebookAuthButton(
// onPressed: () {
// setState(() {
// isLoading = !isLoading;
// });
// },
// isLoading: isLoading,
// style: AuthButtonStyle(
// buttonColor: Colors.blue[900],
// textStyle: const TextStyle(
// fontSize: 16,
// color: Colors.white,
// fontWeight: FontWeight.bold),
// width: 350.0,
// height: 45.0,
// ),
// ),
// ),
],
),
),
),
],
),
);
}
// Future<void> signIn() async {
// if (_formKey.currentState!.validate()) {
// _formKey.currentState!.save();
// try {
// UserCredential userCredential = await _auth.signInWithEmailAndPassword(
// email: _email,
// password: _password,
// );
// Navigator.pushReplacement(
// context,
// MaterialPageRoute(builder: (context) => MyBottomNavigationBar()),
// );
// } on FirebaseAuthException catch (e) {
// if (e.code == 'user-not-found') {
// debugPrint('No user found for that email.');
// } else if (e.code == 'wrong-password') {
// debugPrint('Wrong password provided for that user.');
// }
// // TODO: Handle other errors
// }
// }
// }
}