Files
afterwork/lib/presentation/screens/signup/SignUpScreen.dart
2024-09-24 00:32:20 +00:00

397 lines
15 KiB
Dart

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:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:loading_icon_button/loading_icon_button.dart';
import 'package:provider/provider.dart';
import '../../../core/theme/theme_provider.dart';
/// Écran d'inscription pour l'application AfterWork.
/// Permet à l'utilisateur de créer un nouveau compte avec des champs comme nom, prénom, email, mot de passe.
class SignUpScreen extends StatefulWidget {
const SignUpScreen({super.key});
@override
_SignUpScreenState createState() => _SignUpScreenState();
}
class _SignUpScreenState extends State<SignUpScreen> {
final _formKey = GlobalKey<FormState>(); // Clé pour valider le formulaire
// Champs utilisateur
String _nom = ''; // Nom de l'utilisateur
String _prenoms = ''; // Prénom de l'utilisateur
String _email = ''; // Email de l'utilisateur
String _password = ''; // Mot de passe de l'utilisateur
String _confirmPassword = ''; // Confirmation du mot de passe
// États de gestion
bool _isPasswordVisible = false; // Pour afficher/masquer le mot de passe
bool _isSubmitting = false; // Indicateur pour l'état de soumission du formulaire
bool _showErrorMessage = false; // Affichage des erreurs
// Services pour les opérations
final UserRemoteDataSource _userRemoteDataSource = UserRemoteDataSource(http.Client());
final SecureStorage _secureStorage = SecureStorage();
final PreferencesHelper _preferencesHelper = PreferencesHelper();
// Contrôleur pour le bouton de chargement
final _btnController = LoadingButtonController();
@override
void dispose() {
_btnController.reset();
super.dispose();
}
/// Fonction pour basculer la visibilité du mot de passe
void _togglePasswordVisibility() {
setState(() {
_isPasswordVisible = !_isPasswordVisible;
});
print("Visibilité du mot de passe basculée: $_isPasswordVisible");
}
Future<void> _submit() async {
print("Tentative de soumission du formulaire d'inscription.");
if (_formKey.currentState!.validate()) {
setState(() {
_isSubmitting = true;
_showErrorMessage = false;
});
_formKey.currentState!.save();
// Vérifier si le mot de passe et la confirmation correspondent
if (_password != _confirmPassword) {
setState(() {
_showErrorMessage = true;
});
print("Les mots de passe ne correspondent pas.");
_btnController.reset();
return;
}
try {
_btnController.start();
// Créer l'utilisateur avec les informations fournies
final UserModel user = UserModel(
userId: '', // L'ID sera généré côté serveur
nom: _nom,
prenoms: _prenoms,
email: _email,
motDePasse: _password, // Le mot de passe sera envoyé en clair pour l'instant
);
// Envoi des informations pour créer un nouvel utilisateur
final createdUser = await _userRemoteDataSource.createUser(user);
if (createdUser == null) {
throw Exception("La création du compte a échoué.");
}
print("Utilisateur créé : ${createdUser.userId}");
// Sauvegarder les informations de l'utilisateur
await _secureStorage.saveUserId(createdUser.userId);
await _preferencesHelper.saveUserName(createdUser.nom);
await _preferencesHelper.saveUserLastName(createdUser.prenoms);
// Rediriger vers la page d'accueil ou une page de confirmation
Navigator.pushReplacementNamed(context, '/home');
} catch (e) {
print("Erreur lors de la création du compte : $e");
_btnController.error();
setState(() {
_showErrorMessage = true;
});
} finally {
_btnController.reset();
setState(() {
_isSubmitting = false;
});
}
} else {
print("Échec de validation du formulaire.");
_btnController.reset();
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context); // Utilisation du thème global
final size = MediaQuery.of(context).size;
final themeProvider = Provider.of<ThemeProvider>(context);
// Vérification si le clavier est visible
bool isKeyboardVisible = MediaQuery.of(context).viewInsets.bottom != 0;
return Scaffold(
body: Stack(
children: [
// Arrière-plan animé avec un dégradé basé sur le thème
AnimatedContainer(
duration: const Duration(seconds: 3),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
theme.colorScheme.primary,
theme.colorScheme.secondary
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
),
),
if (_isSubmitting)
const Center(
child: CircularProgressIndicator(),
),
// Bouton pour basculer entre les modes jour et nuit
Positioned(
top: 40,
right: 20,
child: IconButton(
icon: Icon(
themeProvider.isDarkMode ? Icons.dark_mode : Icons.light_mode,
color: theme.iconTheme.color,
),
onPressed: () {
themeProvider.toggleTheme();
print("Thème basculé : ${themeProvider.isDarkMode ? 'Sombre' : 'Clair'}");
},
),
),
// Formulaire d'inscription
Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// Logo de l'application
Image.asset(
'lib/assets/images/logo.png',
height: size.height * 0.25,
),
const SizedBox(height: 20),
// Titre de la page
Text(
'Créer un compte AfterWork',
style: theme.textTheme.titleLarge,
),
const SizedBox(height: 40),
// Champ nom
_buildTextFormField(
label: 'Nom',
icon: Icons.person,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Veuillez entrer votre nom';
}
return null;
},
onSaved: (value) {
_nom = value!;
},
),
const SizedBox(height: 20),
// Champ prénom
_buildTextFormField(
label: 'Prénoms',
icon: Icons.person_outline,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Veuillez entrer votre prénom';
}
return null;
},
onSaved: (value) {
_prenoms = value!;
},
),
const SizedBox(height: 20),
// Champ email
_buildTextFormField(
label: 'Email',
icon: Icons.email,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Veuillez entrer votre email';
}
if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
return 'Veuillez entrer un email valide';
}
return null;
},
onSaved: (value) {
_email = value!;
},
),
const SizedBox(height: 20),
// Champ mot de passe
_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) {
return 'Veuillez entrer votre mot de passe';
}
if (value.length < 6) {
return 'Le mot de passe doit comporter au moins 6 caractères';
}
return null;
},
onSaved: (value) {
_password = value!;
},
),
const SizedBox(height: 20),
// Champ de confirmation du mot de passe
_buildTextFormField(
label: 'Confirmer le mot de passe',
icon: Icons.lock_outline,
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) {
return 'Veuillez confirmer votre mot de passe';
}
if (value != _password) {
return 'Les mots de passe ne correspondent pas';
}
return null;
},
onSaved: (value) {
_confirmPassword = value!;
},
),
const SizedBox(height: 30),
// Bouton de création de compte
SizedBox(
width: size.width * 0.85,
child: LoadingButton(
controller: _btnController,
onPressed: _isSubmitting ? null : _submit,
iconData: Icons.person_add,
iconColor: theme.colorScheme.onPrimary,
child: Text(
'Créer un compte',
style: theme.textTheme.bodyLarge!.copyWith(
color: theme.colorScheme.onPrimary,
),
),
),
),
const SizedBox(height: 20),
// Lien pour revenir à la connexion
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(
'Déjà un compte ? Connectez-vous',
style: theme.textTheme.bodyMedium!
.copyWith(color: Colors.white70),
),
),
// Affichage du message d'erreur si nécessaire
if (_showErrorMessage)
const Padding(
padding: EdgeInsets.only(top: 20),
child: Text(
'Erreur lors de la création du compte. Veuillez vérifier vos informations.',
style: TextStyle(color: Colors.red, fontSize: 16),
textAlign: TextAlign.center,
),
),
],
),
),
),
),
// Pied de page avec logo et mention copyright
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 LionsDev',
style: theme.textTheme.bodyMedium!
.copyWith(color: Colors.white70),
textAlign: TextAlign.center,
),
],
),
),
],
),
);
}
/// Widget réutilisable pour les champs de texte avec validation et design amélioré
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); // Utilisation du thème global
return TextFormField(
decoration: InputDecoration(
labelText: label,
filled: true,
fillColor: theme.inputDecorationTheme.fillColor,
labelStyle: theme.textTheme.bodyMedium,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12.0),
borderSide: BorderSide.none,
),
prefixIcon: Icon(icon, color: theme.iconTheme.color),
suffixIcon: suffixIcon,
),
obscureText: obscureText,
style: theme.textTheme.bodyLarge,
validator: validator,
onSaved: onSaved,
);
}
}