// lib/pages/login_page.
dart
import 'package:flutter/material.dart';
import 'package:appwrite/appwrite.dart';
import 'package:appwrite/models.dart' as models;
import '../services/appwrite_service.dart'; // Assuming
AppwriteService contains your Appwrite initialization
class LoginPage extends StatefulWidget {
const LoginPage({Key? key}) : super(key: key);
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> with
WidgetsBindingObserver {
bool _isLoading = false;
final _formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
bool _obscurePassword = true;
String _selectedUserType = ' ;'طالب// Default to student
final List<String> _userTypes = [' 'مسؤول,' 'دكتور,';]'طالب
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) async {
if (state == AppLifecycleState.detached || state ==
AppLifecycleState.paused) {
try {
await AppwriteService.account.deleteSession(sessionId:
'current');
} catch (e) {
// Ignore errors when deleting the session
}
}
}
void _login() async {
if (_formKey.currentState!.validate()) {
setState(() {
_isLoading = true;
});
try {
// Ensure any existing sessions are cleared
await AppwriteService.account.deleteSession(sessionId:
'current');
// Capture email and password
String email = _emailController.text.trim();
String password = _passwordController.text;
// Log the user in using email/password
await
AppwriteService.account.createEmailPasswordSession(email: email,
password: password);
// Retrieve the current logged-in user
final user = await AppwriteService.account.get();
// Fetch user role from the database (custom collection
'user_roles')
final roleDoc = await AppwriteService.database.listDocuments(
databaseId: 'your_database_id', // Replace with your actual
database ID
collectionId: 'user_roles', // Replace with your actual
collection ID
queries: [
Query.equal('userId', user.$id),
],
);
// Default user role to '( 'طالبstudent)
String userRole = ';'طالب
if (roleDoc.documents.isNotEmpty) {
userRole = roleDoc.documents.first.data['role'];
}
// Show login success message
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(''تم تسجيل الدخول بنجاح, textAlign:
TextAlign.right),
backgroundColor: Colors.green,
),
);
// Navigate to the appropriate screen based on the user role
if (userRole == '{ )'طالب
Navigator.pushReplacementNamed(context, '/student');
} else if (userRole == '{ )'دكتور
Navigator.pushReplacementNamed(context, '/teacher');
} else if (userRole == '{ )'مسؤول
Navigator.pushReplacementNamed(context, '/admin');
} else {
// Handle unexpected roles
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(''دور المستخدم غير معروف, textAlign:
TextAlign.right),
backgroundColor: Colors.red,
),
);
}
} on AppwriteException catch (e) {
// Handle Appwrite exceptions (e.g., incorrect login, network
issues)
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
e.message ?? ''حدث خطأ أثناء تسجيل الدخول,
textAlign: TextAlign.right,
),
backgroundColor: Colors.red,
),
);
} catch (e) {
// Handle any other exceptions
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(''حدث خطأ غير متوقع, textAlign:
TextAlign.right),
backgroundColor: Colors.red,
),
);
} finally {
setState(() {
_isLoading = false;
});
}
}
}
Widget _buildInputField({
required String label,
required TextEditingController controller,
required IconData icon,
required String hintText,
}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('$label:', style: const TextStyle(fontWeight:
FontWeight.bold)),
const SizedBox(height: 5),
Container(
height: 50,
decoration: BoxDecoration(
color: const Color(0xFF3F51B5),
borderRadius: BorderRadius.circular(10),
),
child: TextFormField(
controller: controller,
textAlign: TextAlign.right,
textAlignVertical: TextAlignVertical.center,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
hintText: hintText,
hintStyle: const TextStyle(color: Colors.white70),
suffixIcon: Icon(icon, color: Colors.white),
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(horizontal:
15, vertical: 0),
isDense: true,
),
validator: (value) {
if (value == null || value.isEmpty) {
return ';'هذا الحقل مطلوب
}
if (controller == _emailController && !
value.contains('@')) {
return ';'يرجى إدخال بريد إلكتروني صحيح
}
return null;
},
),
),
],
);
}
Widget _buildPasswordField() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('كلمة المرور:', style: TextStyle(fontWeight:
FontWeight.bold)),
const SizedBox(height: 5),
Container(
height: 50,
decoration: BoxDecoration(
color: const Color(0xFF3F51B5),
borderRadius: BorderRadius.circular(10),
),
child: TextFormField(
controller: _passwordController,
obscureText: _obscurePassword,
textAlign: TextAlign.right,
textAlignVertical: TextAlignVertical.center,
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
hintText: ''أدخل كلمة المرور,
hintStyle: const TextStyle(color: Colors.white70),
suffixIcon: Icon(Icons.lock, color: Colors.white),
prefixIcon: IconButton(
icon: Icon(
_obscurePassword ? Icons.visibility :
Icons.visibility_off,
color: Colors.white,
),
onPressed: () {
setState(() {
_obscurePassword = !_obscurePassword;
});
},
),
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(horizontal:
15, vertical: 15),
isDense: true,
),
validator: (value) {
if (value == null || value.isEmpty) {
return ';'كلمة المرور مطلوبة
}
return null;
},
),
),
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Directionality(
textDirection: TextDirection.rtl,
child: Container(
decoration: BoxDecoration(
border: Border.all(color: const Color(0xFF3F51B5), width:
2),
),
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Align(
alignment: Alignment.topRight,
child: Padding(
padding: const EdgeInsets.only(bottom: 20.0),
child: Icon(
Icons.school,
size: 40,
color: const Color(0xFF3F51B5),
),
),
),
const Icon(
Icons.account_circle,
size: 80,
color: Color(0xFF3F51B5),
),
const SizedBox(height: 10),
const Text(
''تسجيل الدخول,
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Color(0xFF3F51B5),
),
),
const SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: _userTypes.map((type) {
final bool isSelected = _selectedUserType ==
type;
return Padding(
padding: const
EdgeInsets.symmetric(horizontal: 6.0),
child: GestureDetector(
onTap: () {
setState(() {
_selectedUserType = type;
});
},
child: Container(
padding: const
EdgeInsets.symmetric(horizontal: 18, vertical: 8),
decoration: BoxDecoration(
color: isSelected ? const
Color(0xFF3F51B5) : Colors.transparent,
border: Border.all(color: const
Color(0xFF3F51B5), width: 2),
borderRadius:
BorderRadius.circular(25),
),
child: Text(
type,
style: TextStyle(
color: isSelected ? Colors.white :
const Color(0xFF3F51B5),
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
),
),
);
}).toList(),
),
const SizedBox(height: 20),
_buildInputField(
label: ''البريد اإللكتروني,
controller: _emailController,
icon: Icons.email,
hintText: ''أدخل البريد اإللكتروني,
),
const SizedBox(height: 20),
_buildPasswordField(),
Align(
alignment: Alignment.centerLeft,
child: TextButton.icon(
onPressed: () {}, // Add Forgot Password
functionality
label: const Text(')'نسيت كلمة المرور؟,
icon: const Icon(Icons.help_outline, size:
16),
),
),
const SizedBox(height: 30),
SizedBox(
width: double.infinity,
height: 50,
child: ElevatedButton(
onPressed: _isLoading ? null : _login,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF3F51B5),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
child: _isLoading
? const CircularProgressIndicator(color:
Colors.white)
: const Text(
''تسجيل الدخول,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
],
),
),
),
),
),
),
);
}
}
import 'package:appwrite/appwrite.dart';
class AppwriteService {
static late Client client;
static late Account account;
static late Databases database; // <-- Add this line
// Initialize the client, account, and database
static void init() {
client = Client()
..setEndpoint('https://fra.cloud.appwrite.io/v1') // Appwrite
endpoint
..setProject('680bc89c000a777f50b7'); // Appwrite project ID
account = Account(client);
database = Databases(client); // <-- Add this line
} // End of init() method
} // End of AppwriteService class