// lib/pages/login_page.
dart
import 'package:flutter/[Link]';
import 'package:appwrite/[Link]';
import 'package:appwrite/[Link]' 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() {
[Link]();
[Link](this);
}
@override
void dispose() {
[Link](this);
_emailController.dispose();
_passwordController.dispose();
[Link]();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) async {
if (state == [Link] || state ==
[Link]) {
try {
await [Link](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 [Link](sessionId:
'current');
// Capture email and password
String email = _emailController.[Link]();
String password = _passwordController.text;
// Log the user in using email/password
await
[Link](email: email,
password: password);
// Retrieve the current logged-in user
final user = await [Link]();
// Fetch user role from the database (custom collection
'user_roles')
final roleDoc = await [Link](
databaseId: 'your_database_id', // Replace with your actual
database ID
collectionId: 'user_roles', // Replace with your actual
collection ID
queries: [
[Link]('userId', user.$id),
],
);
// Default user role to '( 'طالبstudent)
String userRole = ';'طالب
if ([Link]) {
userRole = [Link]['role'];
}
// Show login success message
[Link](context).showSnackBar(
const SnackBar(
content: Text(''تم تسجيل الدخول بنجاح, textAlign:
[Link]),
backgroundColor: [Link],
),
);
// Navigate to the appropriate screen based on the user role
if (userRole == '{ )'طالب
[Link](context, '/student');
} else if (userRole == '{ )'دكتور
[Link](context, '/teacher');
} else if (userRole == '{ )'مسؤول
[Link](context, '/admin');
} else {
// Handle unexpected roles
[Link](context).showSnackBar(
const SnackBar(
content: Text(''دور المستخدم غير معروف, textAlign:
[Link]),
backgroundColor: [Link],
),
);
}
} on AppwriteException catch (e) {
// Handle Appwrite exceptions (e.g., incorrect login, network
issues)
[Link](context).showSnackBar(
SnackBar(
content: Text(
[Link] ?? ''حدث خطأ أثناء تسجيل الدخول,
textAlign: [Link],
),
backgroundColor: [Link],
),
);
} catch (e) {
// Handle any other exceptions
[Link](context).showSnackBar(
const SnackBar(
content: Text(''حدث خطأ غير متوقع, textAlign:
[Link]),
backgroundColor: [Link],
),
);
} finally {
setState(() {
_isLoading = false;
});
}
}
}
Widget _buildInputField({
required String label,
required TextEditingController controller,
required IconData icon,
required String hintText,
}) {
return Column(
crossAxisAlignment: [Link],
children: [
Text('$label:', style: const TextStyle(fontWeight:
[Link])),
const SizedBox(height: 5),
Container(
height: 50,
decoration: BoxDecoration(
color: const Color(0xFF3F51B5),
borderRadius: [Link](10),
),
child: TextFormField(
controller: controller,
textAlign: [Link],
textAlignVertical: [Link],
style: const TextStyle(color: [Link]),
decoration: InputDecoration(
hintText: hintText,
hintStyle: const TextStyle(color: Colors.white70),
suffixIcon: Icon(icon, color: [Link]),
border: [Link],
contentPadding: const [Link](horizontal:
15, vertical: 0),
isDense: true,
),
validator: (value) {
if (value == null || [Link]) {
return ';'هذا الحقل مطلوب
}
if (controller == _emailController && !
[Link]('@')) {
return ';'يرجى إدخال بريد إلكتروني صحيح
}
return null;
},
),
),
],
);
}
Widget _buildPasswordField() {
return Column(
crossAxisAlignment: [Link],
children: [
const Text('كلمة المرور:', style: TextStyle(fontWeight:
[Link])),
const SizedBox(height: 5),
Container(
height: 50,
decoration: BoxDecoration(
color: const Color(0xFF3F51B5),
borderRadius: [Link](10),
),
child: TextFormField(
controller: _passwordController,
obscureText: _obscurePassword,
textAlign: [Link],
textAlignVertical: [Link],
style: const TextStyle(color: [Link]),
decoration: InputDecoration(
hintText: ''أدخل كلمة المرور,
hintStyle: const TextStyle(color: Colors.white70),
suffixIcon: Icon([Link], color: [Link]),
prefixIcon: IconButton(
icon: Icon(
_obscurePassword ? [Link] :
Icons.visibility_off,
color: [Link],
),
onPressed: () {
setState(() {
_obscurePassword = !_obscurePassword;
});
},
),
border: [Link],
contentPadding: const [Link](horizontal:
15, vertical: 15),
isDense: true,
),
validator: (value) {
if (value == null || [Link]) {
return ';'كلمة المرور مطلوبة
}
return null;
},
),
),
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Directionality(
textDirection: [Link],
child: Container(
decoration: BoxDecoration(
border: [Link](color: const Color(0xFF3F51B5), width:
2),
),
child: SingleChildScrollView(
child: Padding(
padding: const [Link](20.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: [Link],
children: [
Align(
alignment: [Link],
child: Padding(
padding: const [Link](bottom: 20.0),
child: Icon(
[Link],
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: [Link],
color: Color(0xFF3F51B5),
),
),
const SizedBox(height: 30),
Row(
mainAxisAlignment: [Link],
children: _userTypes.map((type) {
final bool isSelected = _selectedUserType ==
type;
return Padding(
padding: const
[Link](horizontal: 6.0),
child: GestureDetector(
onTap: () {
setState(() {
_selectedUserType = type;
});
},
child: Container(
padding: const
[Link](horizontal: 18, vertical: 8),
decoration: BoxDecoration(
color: isSelected ? const
Color(0xFF3F51B5) : [Link],
border: [Link](color: const
Color(0xFF3F51B5), width: 2),
borderRadius:
[Link](25),
),
child: Text(
type,
style: TextStyle(
color: isSelected ? [Link] :
const Color(0xFF3F51B5),
fontWeight: [Link],
fontSize: 16,
),
),
),
),
);
}).toList(),
),
const SizedBox(height: 20),
_buildInputField(
label: ''البريد اإللكتروني,
controller: _emailController,
icon: [Link],
hintText: ''أدخل البريد اإللكتروني,
),
const SizedBox(height: 20),
_buildPasswordField(),
Align(
alignment: [Link],
child: [Link](
onPressed: () {}, // Add Forgot Password
functionality
label: const Text(')'نسيت كلمة المرور؟,
icon: const Icon(Icons.help_outline, size:
16),
),
),
const SizedBox(height: 30),
SizedBox(
width: [Link],
height: 50,
child: ElevatedButton(
onPressed: _isLoading ? null : _login,
style: [Link](
backgroundColor: const Color(0xFF3F51B5),
shape: RoundedRectangleBorder(
borderRadius: [Link](10),
),
),
child: _isLoading
? const CircularProgressIndicator(color:
[Link])
: const Text(
''تسجيل الدخول,
style: TextStyle(
fontSize: 18,
fontWeight: [Link],
color: [Link],
),
),
),
),
],
),
),
),
),
),
),
);
}
}
import 'package:appwrite/[Link]';
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('[Link] // Appwrite
endpoint
..setProject('680bc89c000a777f50b7'); // Appwrite project ID
account = Account(client);
database = Databases(client); // <-- Add this line
} // End of init() method
} // End of AppwriteService class