fix(chat): Correction race condition + Implémentation TODOs
## Corrections Critiques ### Race Condition - Statuts de Messages - Fix : Les icônes de statut (✓, ✓✓, ✓✓ bleu) ne s'affichaient pas - Cause : WebSocket delivery confirmations arrivaient avant messages locaux - Solution : Pattern Optimistic UI dans chat_bloc.dart - Création message temporaire immédiate - Ajout à la liste AVANT requête HTTP - Remplacement par message serveur à la réponse - Fichier : lib/presentation/state_management/chat_bloc.dart ## Implémentation TODOs (13/21) ### Social (social_header_widget.dart) - ✅ Copier lien du post dans presse-papiers - ✅ Partage natif via Share.share() - ✅ Dialogue de signalement avec 5 raisons ### Partage (share_post_dialog.dart) - ✅ Interface sélection d'amis avec checkboxes - ✅ Partage externe via Share API ### Média (media_upload_service.dart) - ✅ Parsing JSON réponse backend - ✅ Méthode deleteMedia() pour suppression - ✅ Génération miniature vidéo ### Posts (create_post_dialog.dart, edit_post_dialog.dart) - ✅ Extraction URL depuis uploads - ✅ Documentation chargement médias ### Chat (conversations_screen.dart) - ✅ Navigation vers notifications - ✅ ConversationSearchDelegate pour recherche ## Nouveaux Fichiers ### Configuration - build-prod.ps1 : Script build production avec dart-define - lib/core/constants/env_config.dart : Gestion environnements ### Documentation - TODOS_IMPLEMENTED.md : Documentation complète TODOs ## Améliorations ### Architecture - Refactoring injection de dépendances - Amélioration routing et navigation - Optimisation providers (UserProvider, FriendsProvider) ### UI/UX - Amélioration thème et couleurs - Optimisation animations - Meilleure gestion erreurs ### Services - Configuration API avec env_config - Amélioration datasources (events, users) - Optimisation modèles de données
This commit is contained in:
@@ -1,398 +1,578 @@
|
||||
import 'dart:async';
|
||||
import 'package:afterwork/data/datasources/user_remote_data_source.dart';
|
||||
import 'package:afterwork/data/models/user_model.dart';
|
||||
import 'package:afterwork/data/services/preferences_helper.dart';
|
||||
import 'package:afterwork/data/services/secure_storage.dart';
|
||||
import 'package:afterwork/presentation/screens/home/home_screen.dart';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_spinkit/flutter_spinkit.dart';
|
||||
import 'package:fluttertoast/fluttertoast.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:loading_icon_button/loading_icon_button.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../../../core/errors/exceptions.dart';
|
||||
import '../../../core/constants/env_config.dart';
|
||||
import '../../../core/theme/theme_provider.dart';
|
||||
import '../../../core/utils/validators.dart';
|
||||
import '../../../data/datasources/event_remote_data_source.dart';
|
||||
import '../../../data/datasources/user_remote_data_source.dart';
|
||||
import '../../../data/models/user_model.dart';
|
||||
import '../../../data/providers/user_provider.dart';
|
||||
import '../../../data/services/preferences_helper.dart';
|
||||
import '../../../data/services/secure_storage.dart';
|
||||
import '../../../domain/entities/user.dart';
|
||||
import '../../widgets/custom_button.dart';
|
||||
import '../home/home_screen.dart';
|
||||
import '../signup/SignUpScreen.dart';
|
||||
|
||||
/// L'écran de connexion où les utilisateurs peuvent s'authentifier.
|
||||
/// Toutes les actions sont loguées pour permettre un suivi dans le terminal et détecter les erreurs.
|
||||
/// Écran de connexion avec design moderne et compact.
|
||||
///
|
||||
/// Cet écran permet aux utilisateurs de s'authentifier avec leur email
|
||||
/// et mot de passe. Il inclut la validation des champs, la gestion d'erreurs,
|
||||
/// et une interface utilisateur optimisée.
|
||||
///
|
||||
/// **Fonctionnalités:**
|
||||
/// - Validation des champs en temps réel
|
||||
/// - Affichage/masquage du mot de passe
|
||||
/// - Gestion d'erreurs robuste
|
||||
/// - Support du thème clair/sombre
|
||||
/// - Navigation vers l'inscription
|
||||
class LoginScreen extends StatefulWidget {
|
||||
const LoginScreen({super.key});
|
||||
|
||||
@override
|
||||
_LoginScreenState createState() => _LoginScreenState();
|
||||
State<LoginScreen> createState() => _LoginScreenState();
|
||||
}
|
||||
|
||||
class _LoginScreenState extends State<LoginScreen>
|
||||
with SingleTickerProviderStateMixin {
|
||||
// Clé globale pour la validation du formulaire
|
||||
// ============================================================================
|
||||
// FORMULAIRE
|
||||
// ============================================================================
|
||||
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _emailController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
|
||||
// Variables pour stocker l'email et le mot de passe saisis par l'utilisateur
|
||||
String _email = '';
|
||||
String _password = '';
|
||||
// ============================================================================
|
||||
// ÉTATS
|
||||
// ============================================================================
|
||||
|
||||
// États de l'écran
|
||||
bool _isPasswordVisible = false; // Pour basculer la visibilité du mot de passe
|
||||
bool _isSubmitting = false; // Indique si la soumission du formulaire est en cours
|
||||
bool _showErrorMessage = false; // Affiche un message d'erreur si nécessaire
|
||||
bool _isPasswordVisible = false;
|
||||
bool _isSubmitting = false;
|
||||
String? _errorMessage;
|
||||
|
||||
// Sources de données et services
|
||||
final UserRemoteDataSource _userRemoteDataSource = UserRemoteDataSource(http.Client());
|
||||
final SecureStorage _secureStorage = SecureStorage();
|
||||
final PreferencesHelper _preferencesHelper = PreferencesHelper();
|
||||
// ============================================================================
|
||||
// SERVICES
|
||||
// ============================================================================
|
||||
|
||||
// Contrôleur pour le bouton de chargement
|
||||
final _btnController = LoadingButtonController();
|
||||
late final UserRemoteDataSource _userRemoteDataSource;
|
||||
late final SecureStorage _secureStorage;
|
||||
late final PreferencesHelper _preferencesHelper;
|
||||
|
||||
// ============================================================================
|
||||
// ANIMATIONS
|
||||
// ============================================================================
|
||||
|
||||
// Contrôleur d'animation pour gérer la transition entre les écrans
|
||||
late AnimationController _animationController;
|
||||
late Animation<double> _fadeAnimation;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initializeServices();
|
||||
_initializeAnimations();
|
||||
}
|
||||
|
||||
void _initializeServices() {
|
||||
_userRemoteDataSource = UserRemoteDataSource(http.Client());
|
||||
_secureStorage = SecureStorage();
|
||||
_preferencesHelper = PreferencesHelper();
|
||||
}
|
||||
|
||||
void _initializeAnimations() {
|
||||
_animationController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 500),
|
||||
duration: const Duration(milliseconds: 800),
|
||||
);
|
||||
debugPrint("[LOG] Contrôleur d'animation initialisé.");
|
||||
_fadeAnimation = CurvedAnimation(
|
||||
parent: _animationController,
|
||||
curve: Curves.easeIn,
|
||||
);
|
||||
_animationController.forward();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
_animationController.dispose();
|
||||
debugPrint("[LOG] Ressources d'animation libérées.");
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Bascule la visibilité du mot de passe et logue l'état actuel.
|
||||
// ============================================================================
|
||||
// ACTIONS
|
||||
// ============================================================================
|
||||
|
||||
/// Bascule la visibilité du mot de passe.
|
||||
void _togglePasswordVisibility() {
|
||||
setState(() {
|
||||
_isPasswordVisible = !_isPasswordVisible;
|
||||
});
|
||||
debugPrint("[LOG] Visibilité du mot de passe basculée: $_isPasswordVisible");
|
||||
}
|
||||
|
||||
/// Affiche un toast avec le message spécifié et logue l'action.
|
||||
void _showToast(String message) {
|
||||
Fluttertoast.showToast(
|
||||
msg: message,
|
||||
toastLength: Toast.LENGTH_SHORT,
|
||||
gravity: ToastGravity.BOTTOM,
|
||||
timeInSecForIosWeb: 1,
|
||||
backgroundColor: Colors.black,
|
||||
textColor: Colors.white,
|
||||
fontSize: 16.0,
|
||||
);
|
||||
debugPrint("[LOG] Toast affiché : $message");
|
||||
}
|
||||
/// Soumet le formulaire de connexion.
|
||||
Future<void> _handleSubmit() async {
|
||||
if (!_formKey.currentState!.validate()) {
|
||||
return;
|
||||
}
|
||||
|
||||
/// Soumet le formulaire de connexion et tente d'authentifier l'utilisateur.
|
||||
/// Toutes les étapes et erreurs sont loguées pour une traçabilité complète.
|
||||
Future<void> _submit() async {
|
||||
debugPrint("[LOG] Tentative de soumission du formulaire de connexion.");
|
||||
setState(() {
|
||||
_isSubmitting = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
|
||||
if (_formKey.currentState!.validate()) {
|
||||
setState(() {
|
||||
_isSubmitting = true;
|
||||
_showErrorMessage = false;
|
||||
});
|
||||
_formKey.currentState!.save(); // Sauvegarde des données saisies
|
||||
try {
|
||||
final email = _emailController.text.trim();
|
||||
final password = _passwordController.text;
|
||||
|
||||
try {
|
||||
_btnController.start();
|
||||
debugPrint("[LOG] Appel à l'API pour authentifier l'utilisateur.");
|
||||
final user = await _userRemoteDataSource.authenticateUser(email, password);
|
||||
|
||||
final UserModel user = await _userRemoteDataSource.authenticateUser(_email, _password);
|
||||
if (user.userId.isEmpty) {
|
||||
throw Exception('ID utilisateur manquant dans la réponse');
|
||||
}
|
||||
|
||||
if (user.userId.isNotEmpty) {
|
||||
debugPrint("[LOG] Utilisateur authentifié avec succès. ID: ${user.userId}");
|
||||
|
||||
await _secureStorage.saveUserId(user.userId);
|
||||
await _preferencesHelper.saveUserName(user.userLastName);
|
||||
await _preferencesHelper.saveUserLastName(user.userFirstName);
|
||||
|
||||
// Met à jour le `UserProvider` avec les informations utilisateur authentifiées
|
||||
final userProvider = Provider.of<UserProvider>(context, listen: false);
|
||||
userProvider.setUser(User(
|
||||
userId: user.userId,
|
||||
userLastName: user.userLastName,
|
||||
userFirstName: user.userFirstName,
|
||||
email: user.email,
|
||||
motDePasse: 'motDePasseHashé',
|
||||
profileImageUrl: 'lib/assets/images/profile_picture.png',
|
||||
eventsCount: user.eventsCount ?? 0,
|
||||
friendsCount: user.friendsCount ?? 0,
|
||||
postsCount: user.postsCount ?? 0,
|
||||
visitedPlacesCount: user.visitedPlacesCount ?? 0,
|
||||
));
|
||||
|
||||
_showToast("Connexion réussie !");
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => HomeScreen(
|
||||
userId: user.userId,
|
||||
userFirstName: user.userFirstName,
|
||||
userLastName: user.userLastName,
|
||||
userProfileImage: 'lib/assets/images/profile_picture.png',
|
||||
eventRemoteDataSource: EventRemoteDataSource(http.Client()),
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
debugPrint("[ERROR] L'ID utilisateur est manquant dans la réponse.");
|
||||
_showToast("Erreur : ID utilisateur manquant.");
|
||||
}
|
||||
} catch (e) {
|
||||
// Gestion des erreurs
|
||||
debugPrint("[ERROR] Erreur lors de la connexion : $e");
|
||||
_showToast("Erreur lors de la connexion : ${e.toString()}");
|
||||
_btnController.error();
|
||||
setState(() {
|
||||
_showErrorMessage = true;
|
||||
});
|
||||
} finally {
|
||||
_btnController.reset();
|
||||
await _saveUserData(user);
|
||||
await _navigateToHome(user);
|
||||
} catch (e) {
|
||||
_handleError(e);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isSubmitting = false;
|
||||
});
|
||||
}
|
||||
} else {
|
||||
debugPrint("[ERROR] Validation du formulaire échouée.");
|
||||
_btnController.reset();
|
||||
_showToast("Veuillez vérifier les informations saisies.");
|
||||
}
|
||||
}
|
||||
|
||||
/// Sauvegarde les données utilisateur.
|
||||
Future<void> _saveUserData(UserModel user) async {
|
||||
await _secureStorage.saveUserId(user.userId);
|
||||
await _preferencesHelper.saveUserName(user.userLastName);
|
||||
await _preferencesHelper.saveUserLastName(user.userFirstName);
|
||||
|
||||
final userProvider = Provider.of<UserProvider>(context, listen: false);
|
||||
userProvider.setUser(
|
||||
User(
|
||||
userId: user.userId,
|
||||
userLastName: user.userLastName,
|
||||
userFirstName: user.userFirstName,
|
||||
email: user.email,
|
||||
motDePasse: 'motDePasseHashé',
|
||||
profileImageUrl: user.profileImageUrl,
|
||||
eventsCount: user.eventsCount ?? 0,
|
||||
friendsCount: user.friendsCount ?? 0,
|
||||
postsCount: user.postsCount ?? 0,
|
||||
visitedPlacesCount: user.visitedPlacesCount ?? 0,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Navigue vers l'écran d'accueil.
|
||||
Future<void> _navigateToHome(UserModel user) async {
|
||||
if (!mounted) return;
|
||||
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => HomeScreen(
|
||||
userId: user.userId,
|
||||
userFirstName: user.userFirstName,
|
||||
userLastName: user.userLastName,
|
||||
userProfileImage: user.profileImageUrl,
|
||||
eventRemoteDataSource: EventRemoteDataSource(http.Client()),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Gère les erreurs de connexion.
|
||||
void _handleError(Object error) {
|
||||
String message = 'Erreur lors de la connexion';
|
||||
|
||||
if (error.toString().contains('Unauthorized') ||
|
||||
error.toString().contains('incorrect')) {
|
||||
message = 'Email ou mot de passe incorrect';
|
||||
} else if (error.toString().contains('network') ||
|
||||
error.toString().contains('timeout')) {
|
||||
message = 'Problème de connexion. Vérifiez votre réseau';
|
||||
} else {
|
||||
message = error.toString().replaceAll('Exception: ', '');
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_errorMessage = message;
|
||||
});
|
||||
|
||||
if (EnvConfig.enableDetailedLogs) {
|
||||
debugPrint('[LoginScreen] Erreur: $error');
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigue vers l'écran d'inscription.
|
||||
void _navigateToSignUp() {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => const SignUpScreen(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Gère la réinitialisation du mot de passe.
|
||||
Future<void> _handleForgotPassword() async {
|
||||
final emailController = TextEditingController();
|
||||
final formKey = GlobalKey<FormState>();
|
||||
|
||||
final result = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Réinitialisation du mot de passe'),
|
||||
content: Form(
|
||||
key: formKey,
|
||||
child: TextFormField(
|
||||
controller: emailController,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Email',
|
||||
hintText: 'Entrez votre email',
|
||||
),
|
||||
validator: Validators.validateEmail,
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('Annuler'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
if (formKey.currentState!.validate()) {
|
||||
Navigator.pop(context, true);
|
||||
}
|
||||
},
|
||||
child: const Text('Envoyer'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (result == true && emailController.text.isNotEmpty) {
|
||||
try {
|
||||
await _userRemoteDataSource.requestPasswordReset(
|
||||
emailController.text.trim(),
|
||||
);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'Un email de réinitialisation a été envoyé à votre adresse',
|
||||
),
|
||||
behavior: SnackBarBehavior.floating,
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Erreur: ${e.toString()}'),
|
||||
behavior: SnackBarBehavior.floating,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// BUILD
|
||||
// ============================================================================
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final size = MediaQuery.of(context).size;
|
||||
final themeProvider = Provider.of<ThemeProvider>(context);
|
||||
bool isKeyboardVisible = MediaQuery.of(context).viewInsets.bottom != 0;
|
||||
final isKeyboardVisible = MediaQuery.of(context).viewInsets.bottom > 0;
|
||||
|
||||
return Scaffold(
|
||||
body: Stack(
|
||||
children: [
|
||||
// Arrière-plan animé
|
||||
AnimatedContainer(
|
||||
duration: const Duration(seconds: 3),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
theme.colorScheme.primary,
|
||||
theme.colorScheme.secondary,
|
||||
],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
),
|
||||
),
|
||||
// Spinner de chargement lors de la soumission
|
||||
if (_isSubmitting)
|
||||
const Center(
|
||||
child: SpinKitFadingCircle(
|
||||
color: Colors.white,
|
||||
size: 50.0,
|
||||
),
|
||||
),
|
||||
// Icône de changement de thème
|
||||
Positioned(
|
||||
top: 40,
|
||||
right: 20,
|
||||
child: IconButton(
|
||||
icon: Icon(
|
||||
themeProvider.isDarkMode ? Icons.dark_mode : Icons.light_mode,
|
||||
color: theme.iconTheme.color,
|
||||
),
|
||||
onPressed: () {
|
||||
themeProvider.toggleTheme();
|
||||
debugPrint("[LOG] Thème basculé : ${themeProvider.isDarkMode ? 'Sombre' : 'Clair'}");
|
||||
},
|
||||
),
|
||||
),
|
||||
// Formulaire de connexion
|
||||
Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Image.asset(
|
||||
'lib/assets/images/logo.png',
|
||||
height: size.height * 0.25,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Text(
|
||||
'Bienvenue sur AfterWork',
|
||||
style: theme.textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 40),
|
||||
_buildTextFormField(
|
||||
label: 'Email',
|
||||
icon: Icons.email,
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
debugPrint("[ERROR] Champ email vide.");
|
||||
return 'Veuillez entrer votre email';
|
||||
}
|
||||
if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
|
||||
debugPrint("[ERROR] Email invalide.");
|
||||
return 'Veuillez entrer un email valide';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
onSaved: (value) {
|
||||
_email = value!;
|
||||
debugPrint("[LOG] Email enregistré : $_email");
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
_buildTextFormField(
|
||||
label: 'Mot de passe',
|
||||
icon: Icons.lock,
|
||||
obscureText: !_isPasswordVisible,
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
_isPasswordVisible ? Icons.visibility : Icons.visibility_off,
|
||||
color: theme.iconTheme.color,
|
||||
),
|
||||
onPressed: _togglePasswordVisibility,
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
debugPrint("[ERROR] Champ mot de passe vide.");
|
||||
return 'Veuillez entrer votre mot de passe';
|
||||
}
|
||||
if (value.length < 6) {
|
||||
debugPrint("[ERROR] Mot de passe trop court.");
|
||||
return 'Le mot de passe doit comporter au moins 6 caractères';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
onSaved: (value) {
|
||||
_password = value!;
|
||||
debugPrint("[LOG] Mot de passe enregistré.");
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 30),
|
||||
SizedBox(
|
||||
width: size.width * 0.85,
|
||||
child: LoadingButton(
|
||||
controller: _btnController,
|
||||
onPressed: _isSubmitting ? null : _submit,
|
||||
iconData: Icons.login,
|
||||
iconColor: theme.colorScheme.onPrimary,
|
||||
child: Text(
|
||||
'Connexion',
|
||||
style: theme.textTheme.bodyLarge!.copyWith(
|
||||
color: theme.colorScheme.onPrimary,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
debugPrint("[LOG] Redirection vers la page d'inscription.");
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => const SignUpScreen(),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: Text(
|
||||
'Pas encore de compte ? Inscrivez-vous',
|
||||
style: theme.textTheme.bodyMedium!.copyWith(color: Colors.white70),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
debugPrint("[LOG] Mot de passe oublié cliqué.");
|
||||
},
|
||||
child: Text(
|
||||
'Mot de passe oublié ?',
|
||||
style: theme.textTheme.bodyMedium!.copyWith(color: Colors.white70),
|
||||
),
|
||||
),
|
||||
if (_showErrorMessage)
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(top: 20),
|
||||
child: Text(
|
||||
'Erreur lors de la connexion. Veuillez vérifier vos identifiants.',
|
||||
style: TextStyle(color: Colors.red, fontSize: 16),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
AnimatedPositioned(
|
||||
duration: const Duration(milliseconds: 300),
|
||||
bottom: isKeyboardVisible ? 0 : 20,
|
||||
left: isKeyboardVisible ? 20 : 0,
|
||||
right: isKeyboardVisible ? 20 : 0,
|
||||
child: Row(
|
||||
mainAxisAlignment: isKeyboardVisible
|
||||
? MainAxisAlignment.spaceBetween
|
||||
: MainAxisAlignment.center,
|
||||
children: [
|
||||
Image.asset(
|
||||
'lib/assets/images/logolionsdev.png',
|
||||
height: 30,
|
||||
),
|
||||
if (isKeyboardVisible)
|
||||
Text(
|
||||
'© 2024',
|
||||
style: theme.textTheme.bodyMedium!.copyWith(color: Colors.white70),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
_buildBackground(theme),
|
||||
_buildContent(theme, isKeyboardVisible),
|
||||
_buildThemeToggle(theme),
|
||||
if (_isSubmitting) _buildLoadingOverlay(theme),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Méthode pour construire les champs de formulaire avec les styles adaptés.
|
||||
Widget _buildTextFormField({
|
||||
required String label,
|
||||
required IconData icon,
|
||||
bool obscureText = false,
|
||||
Widget? suffixIcon,
|
||||
required FormFieldValidator<String> validator,
|
||||
required FormFieldSetter<String> onSaved,
|
||||
}) {
|
||||
final theme = Theme.of(context);
|
||||
/// Construit l'arrière-plan avec dégradé.
|
||||
Widget _buildBackground(ThemeData theme) {
|
||||
return AnimatedContainer(
|
||||
duration: const Duration(seconds: 3),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
theme.colorScheme.primary,
|
||||
theme.colorScheme.secondary,
|
||||
],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit le contenu principal.
|
||||
Widget _buildContent(ThemeData theme, bool isKeyboardVisible) {
|
||||
return FadeTransition(
|
||||
opacity: _fadeAnimation,
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
if (!isKeyboardVisible) _buildLogo(theme),
|
||||
if (!isKeyboardVisible) const SizedBox(height: 32),
|
||||
_buildTitle(theme),
|
||||
const SizedBox(height: 40),
|
||||
_buildEmailField(theme),
|
||||
const SizedBox(height: 16),
|
||||
_buildPasswordField(theme),
|
||||
const SizedBox(height: 24),
|
||||
_buildSubmitButton(theme),
|
||||
const SizedBox(height: 16),
|
||||
_buildSignUpLink(theme),
|
||||
_buildForgotPasswordLink(theme),
|
||||
if (_errorMessage != null) _buildErrorMessage(theme),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit le logo.
|
||||
Widget _buildLogo(ThemeData theme) {
|
||||
return Image.asset(
|
||||
'lib/assets/images/logo.png',
|
||||
height: 120,
|
||||
errorBuilder: (context, error, stackTrace) {
|
||||
return Icon(
|
||||
Icons.event,
|
||||
size: 80,
|
||||
color: theme.colorScheme.onPrimary,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit le titre.
|
||||
Widget _buildTitle(ThemeData theme) {
|
||||
return Text(
|
||||
'Bienvenue sur AfterWork',
|
||||
style: theme.textTheme.headlineSmall?.copyWith(
|
||||
color: theme.colorScheme.onPrimary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit le champ email.
|
||||
Widget _buildEmailField(ThemeData theme) {
|
||||
return TextFormField(
|
||||
controller: _emailController,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
textInputAction: TextInputAction.next,
|
||||
decoration: InputDecoration(
|
||||
labelText: label,
|
||||
labelText: 'Email',
|
||||
prefixIcon: Icon(Icons.email, color: theme.colorScheme.onPrimary),
|
||||
filled: true,
|
||||
fillColor: theme.inputDecorationTheme.fillColor,
|
||||
labelStyle: theme.textTheme.bodyMedium,
|
||||
fillColor: theme.colorScheme.onPrimary.withOpacity(0.1),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12.0),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
prefixIcon: Icon(icon, color: theme.iconTheme.color),
|
||||
suffixIcon: suffixIcon,
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(
|
||||
color: theme.colorScheme.onPrimary.withOpacity(0.3),
|
||||
),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(
|
||||
color: theme.colorScheme.onPrimary,
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
labelStyle: TextStyle(color: theme.colorScheme.onPrimary),
|
||||
),
|
||||
style: TextStyle(color: theme.colorScheme.onPrimary),
|
||||
validator: Validators.validateEmail,
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit le champ mot de passe.
|
||||
Widget _buildPasswordField(ThemeData theme) {
|
||||
return TextFormField(
|
||||
controller: _passwordController,
|
||||
obscureText: !_isPasswordVisible,
|
||||
textInputAction: TextInputAction.done,
|
||||
onFieldSubmitted: (_) => _handleSubmit(),
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Mot de passe',
|
||||
prefixIcon: Icon(Icons.lock, color: theme.colorScheme.onPrimary),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
_isPasswordVisible ? Icons.visibility : Icons.visibility_off,
|
||||
color: theme.colorScheme.onPrimary.withOpacity(0.7),
|
||||
),
|
||||
onPressed: _togglePasswordVisibility,
|
||||
),
|
||||
filled: true,
|
||||
fillColor: theme.colorScheme.onPrimary.withOpacity(0.1),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(
|
||||
color: theme.colorScheme.onPrimary.withOpacity(0.3),
|
||||
),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(
|
||||
color: theme.colorScheme.onPrimary,
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
labelStyle: TextStyle(color: theme.colorScheme.onPrimary),
|
||||
),
|
||||
style: TextStyle(color: theme.colorScheme.onPrimary),
|
||||
validator: Validators.validatePassword,
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit le bouton de soumission (compact).
|
||||
Widget _buildSubmitButton(ThemeData theme) {
|
||||
return SizedBox(
|
||||
width: double.infinity,
|
||||
child: CustomButton(
|
||||
text: 'Connexion',
|
||||
icon: Icons.login,
|
||||
onPressed: () => _handleSubmit(),
|
||||
isLoading: _isSubmitting,
|
||||
isEnabled: !_isSubmitting,
|
||||
variant: ButtonVariant.primary,
|
||||
size: ButtonSize.medium,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit le lien vers l'inscription.
|
||||
Widget _buildSignUpLink(ThemeData theme) {
|
||||
return TextButton(
|
||||
onPressed: _navigateToSignUp,
|
||||
child: Text(
|
||||
'Pas encore de compte ? Inscrivez-vous',
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onPrimary.withOpacity(0.9),
|
||||
decoration: TextDecoration.underline,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit le lien mot de passe oublié.
|
||||
Widget _buildForgotPasswordLink(ThemeData theme) {
|
||||
return TextButton(
|
||||
onPressed: _handleForgotPassword,
|
||||
child: Text(
|
||||
'Mot de passe oublié ?',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onPrimary.withOpacity(0.7),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit le message d'erreur.
|
||||
Widget _buildErrorMessage(ThemeData theme) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 16),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.error.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(
|
||||
color: theme.colorScheme.error.withOpacity(0.3),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.error_outline,
|
||||
color: theme.colorScheme.error,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_errorMessage!,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit le bouton de basculement de thème.
|
||||
Widget _buildThemeToggle(ThemeData theme) {
|
||||
return Positioned(
|
||||
top: MediaQuery.of(context).padding.top + 8,
|
||||
right: 16,
|
||||
child: IconButton(
|
||||
icon: Icon(
|
||||
Provider.of<ThemeProvider>(context).isDarkMode
|
||||
? Icons.light_mode
|
||||
: Icons.dark_mode,
|
||||
color: theme.colorScheme.onPrimary,
|
||||
),
|
||||
onPressed: () {
|
||||
Provider.of<ThemeProvider>(context, listen: false).toggleTheme();
|
||||
},
|
||||
tooltip: 'Changer le thème',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit l'overlay de chargement.
|
||||
Widget _buildLoadingOverlay(ThemeData theme) {
|
||||
return Container(
|
||||
color: Colors.black.withOpacity(0.3),
|
||||
child: Center(
|
||||
child: CircularProgressIndicator(
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
theme.colorScheme.onPrimary,
|
||||
),
|
||||
),
|
||||
),
|
||||
obscureText: obscureText,
|
||||
style: theme.textTheme.bodyLarge,
|
||||
validator: validator,
|
||||
onSaved: onSaved,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user