refactoring and checkpoint
BIN
lib/assets/fonts/montserrat_bold.ttf
Normal file
BIN
lib/assets/fonts/montserrat_regular.ttf
Normal file
BIN
lib/assets/images/activity_placeholder.png
Normal file
|
After Width: | Height: | Size: 1.2 MiB |
BIN
lib/assets/images/event_placeholder.png
Normal file
|
After Width: | Height: | Size: 1.8 MiB |
BIN
lib/assets/images/friend_placeholder.png
Normal file
|
After Width: | Height: | Size: 254 KiB |
BIN
lib/assets/images/group_placeholder.png
Normal file
|
After Width: | Height: | Size: 436 KiB |
|
Before Width: | Height: | Size: 1.8 MiB After Width: | Height: | Size: 1.5 MiB |
BIN
lib/assets/images/logoaw.png
Normal file
|
After Width: | Height: | Size: 1.8 MiB |
BIN
lib/assets/images/logolionsdev.png
Normal file
|
After Width: | Height: | Size: 1.1 MiB |
BIN
lib/assets/images/story_placeholder.png
Normal file
|
After Width: | Height: | Size: 313 KiB |
BIN
lib/assets/images/user_placeholder.png
Normal file
|
After Width: | Height: | Size: 222 KiB |
BIN
lib/assets/videos/test.mp4
Normal file
@@ -5,18 +5,31 @@ import '../../data/datasources/user_remote_data_source.dart';
|
||||
import '../../data/repositories/user_repository_impl.dart';
|
||||
import '../../domain/usecases/get_user.dart';
|
||||
|
||||
/// Instance globale pour gérer l'injection des dépendances via GetIt
|
||||
final sl = GetIt.instance;
|
||||
|
||||
/// Fonction d'initialisation pour enregistrer toutes les dépendances.
|
||||
/// Utilisée pour fournir des services, des data sources, des repositories et des use cases.
|
||||
void init() {
|
||||
// Log de démarrage de l'injection des dépendances
|
||||
print("Démarrage de l'initialisation des dépendances.");
|
||||
|
||||
// Register Http Client
|
||||
sl.registerLazySingleton(() => http.Client());
|
||||
print("Client HTTP enregistré.");
|
||||
|
||||
// Register Data Sources
|
||||
sl.registerLazySingleton(() => UserRemoteDataSource(sl()));
|
||||
print("DataSource pour UserRemoteDataSource enregistré.");
|
||||
|
||||
// Register Repositories
|
||||
sl.registerLazySingleton(() => UserRepositoryImpl(remoteDataSource: sl()));
|
||||
print("Repository pour UserRepositoryImpl enregistré.");
|
||||
|
||||
// Register Use Cases
|
||||
sl.registerLazySingleton(() => GetUser(sl()));
|
||||
print("UseCase pour GetUser enregistré.");
|
||||
|
||||
// Log de fin d'initialisation des dépendances
|
||||
print("Initialisation des dépendances terminée.");
|
||||
}
|
||||
|
||||
@@ -1,30 +1,39 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:afterwork/presentation/screens/login/login_screen.dart';
|
||||
import 'package:afterwork/presentation/screens/home/home_screen.dart';
|
||||
import 'package:afterwork/presentation/screens/event/event_screen.dart';
|
||||
import 'package:afterwork/presentation/screens/story/story_screen.dart';
|
||||
import 'package:afterwork/presentation/screens/profile/profile_screen.dart';
|
||||
import 'package:afterwork/presentation/screens/settings/settings_screen.dart';
|
||||
import 'package:afterwork/presentation/screens/home/home_screen.dart';
|
||||
import 'package:afterwork/data/datasources/event_remote_data_source.dart';
|
||||
import '../presentation/reservations/reservations_screen.dart';
|
||||
|
||||
/// Router personnalisé pour gérer la navigation dans l'application.
|
||||
/// Les logs permettent de tracer chaque navigation dans la console.
|
||||
class AppRouter {
|
||||
final EventRemoteDataSource eventRemoteDataSource;
|
||||
final String userId;
|
||||
final String userName;
|
||||
final String userLastName;
|
||||
|
||||
/// Initialisation des informations utilisateur et source de données
|
||||
AppRouter({
|
||||
required this.eventRemoteDataSource,
|
||||
required this.userId,
|
||||
required this.userName,
|
||||
required this.userLastName,
|
||||
});
|
||||
}) {
|
||||
print("AppRouter initialisé avec les infos utilisateur : $userId, $userName, $userLastName");
|
||||
}
|
||||
|
||||
/// Génération des routes pour l'application
|
||||
Route<dynamic> generateRoute(RouteSettings settings) {
|
||||
print("Navigation vers la route : ${settings.name}");
|
||||
|
||||
switch (settings.name) {
|
||||
case '/':
|
||||
return MaterialPageRoute(builder: (_) => const LoginScreen());
|
||||
|
||||
case '/home':
|
||||
return MaterialPageRoute(
|
||||
builder: (_) => HomeScreen(
|
||||
@@ -32,25 +41,31 @@ class AppRouter {
|
||||
userId: userId,
|
||||
userName: userName,
|
||||
userLastName: userLastName,
|
||||
userProfileImage: 'lib/assets/images/profile_picture.png',
|
||||
),
|
||||
);
|
||||
|
||||
case '/event':
|
||||
return MaterialPageRoute(
|
||||
builder: (_) => EventScreen(
|
||||
eventRemoteDataSource: eventRemoteDataSource,
|
||||
userId: userId,
|
||||
userName: userName,
|
||||
userLastName: userLastName,
|
||||
),
|
||||
);
|
||||
|
||||
case '/story':
|
||||
return MaterialPageRoute(builder: (_) => const StoryScreen());
|
||||
|
||||
case '/profile':
|
||||
return MaterialPageRoute(builder: (_) => const ProfileScreen());
|
||||
|
||||
case '/settings':
|
||||
return MaterialPageRoute(builder: (_) => const SettingsScreen());
|
||||
|
||||
case '/reservations':
|
||||
return MaterialPageRoute(builder: (_) => const ReservationsScreen());
|
||||
|
||||
default:
|
||||
return MaterialPageRoute(
|
||||
builder: (_) => const Scaffold(
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Classe utilitaire pour gérer les couleurs de l'application en mode clair et sombre.
|
||||
class AppColors {
|
||||
// Thème clair
|
||||
static const Color lightPrimary = Color(0xFF0057D9);
|
||||
static const Color lightSecondary = Color(0xFFFFC107);
|
||||
static const Color lightOnPrimary = Colors.white;
|
||||
static const Color lightOnSecondary = Color(0xFF212121);
|
||||
static const Color lightBackground = Colors.white;
|
||||
static const Color lightSurface = Color(0xFFFFFFFF);
|
||||
static const Color lightTextPrimary = Color(0xFF212121);
|
||||
static const Color lightTextSecondary = Color(0xFF616161);
|
||||
static const Color lightCardColor = Color(0xFFFFFFFF);
|
||||
static const Color lightAccentColor = Color(0xFF4CAF50);
|
||||
static const Color lightError = Color(0xFFB00020);
|
||||
static const Color lightIconPrimary = Color(0xFF212121); // Icône primaire sombre
|
||||
static const Color lightIconSecondary = Color(0xFF757575); // Icône secondaire gris clair
|
||||
// Thème sombre
|
||||
static const Color darkPrimary = Color(0xFF121212);
|
||||
static const Color darkSecondary = Color(0xFFFF5722);
|
||||
static const Color darkOnPrimary = Colors.white;
|
||||
static const Color darkOnSecondary = Colors.white;
|
||||
static const Color darkBackground = Color(0xFF121212);
|
||||
static const Color darkSurface = Color(0xFF1F1F1F);
|
||||
static const Color darkTextPrimary = Color(0xFFE0E0E0);
|
||||
static const Color darkTextSecondary = Color(0xFFBDBDBD);
|
||||
static const Color darkCardColor = Color(0xFF2C2C2C);
|
||||
static const Color darkAccentColor = Color(0xFF81C784);
|
||||
static const Color darkError = Color(0xFFCF6679);
|
||||
static const Color darkIconPrimary = Colors.white; // Icône primaire blanche
|
||||
static const Color darkIconSecondary = Color(0xFFBDBDBD); // Icône secondaire gris clair
|
||||
|
||||
// Sélection automatique des couleurs en fonction du mode de thème
|
||||
static Color get primary => isDarkMode() ? darkPrimary : lightPrimary;
|
||||
static Color get secondary => isDarkMode() ? darkSecondary : lightSecondary;
|
||||
static Color get onPrimary => isDarkMode() ? darkOnPrimary : lightOnPrimary;
|
||||
static Color get onSecondary => isDarkMode() ? darkOnSecondary : lightOnSecondary;
|
||||
static Color get backgroundColor => isDarkMode() ? darkBackground : lightBackground;
|
||||
static Color get surface => isDarkMode() ? darkSurface : lightSurface;
|
||||
static Color get textPrimary => isDarkMode() ? darkTextPrimary : lightTextPrimary;
|
||||
static Color get textSecondary => isDarkMode() ? darkTextSecondary : lightTextSecondary;
|
||||
static Color get cardColor => isDarkMode() ? darkCardColor : lightCardColor;
|
||||
static Color get accentColor => isDarkMode() ? darkAccentColor : lightAccentColor;
|
||||
static Color get errorColor => isDarkMode() ? darkError : lightError;
|
||||
static Color get iconPrimary => isDarkMode() ? darkIconPrimary : lightIconPrimary;
|
||||
static Color get iconSecondary => isDarkMode() ? darkIconSecondary : lightIconSecondary;
|
||||
|
||||
/// Méthode utilitaire pour vérifier si le mode sombre est activé.
|
||||
static bool isDarkMode() {
|
||||
final brightness = WidgetsBinding.instance.platformDispatcher.platformBrightness;
|
||||
return brightness == Brightness.dark;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,31 @@
|
||||
class Urls {
|
||||
static const String baseUrl = 'http://192.168.1.145:8085';
|
||||
// static const String login = baseUrl + 'auth/login';
|
||||
static const String eventsUrl = '$baseUrl/events';
|
||||
// Ajoute d'autres URLs ici
|
||||
|
||||
// Authentication and Users Endpoints
|
||||
static const String authenticateUser = '$baseUrl/users/authenticate';
|
||||
static const String createUser = '$baseUrl/users';
|
||||
static const String getUserById = '$baseUrl/users'; // Append '/{id}' dynamically
|
||||
static const String deleteUser = '$baseUrl/users'; // Append '/{id}' dynamically
|
||||
static const String updateUserProfileImage = '$baseUrl/users'; // Append '/{id}/profile-image' dynamically
|
||||
|
||||
// Events Endpoints
|
||||
static const String createEvent = '$baseUrl/events';
|
||||
static const String getEventById = '$baseUrl/events'; // Append '/{id}' dynamically
|
||||
static const String deleteEvent = '$baseUrl/events'; // Append '/{id}' dynamically
|
||||
static const String getEventsAfterDate = '$baseUrl/events/after-date';
|
||||
static const String addParticipant = '$baseUrl/events'; // Append '/{id}/participants' dynamically
|
||||
static const String removeParticipant = '$baseUrl/events'; // Append '/{id}/participants/{userId}' dynamically
|
||||
static const String getNumberOfParticipants = '$baseUrl/events'; // Append '/{id}/participants/count' dynamically
|
||||
static const String closeEvent = '$baseUrl/events'; // Append '/{id}/close' dynamically
|
||||
static const String updateEvent = '$baseUrl/events'; // Append '/{id}' dynamically
|
||||
static const String updateEventImage = '$baseUrl/events'; // Append '/{id}/image' dynamically
|
||||
static const String getAllEvents = '$baseUrl/events';
|
||||
static const String getEventsByCategory = '$baseUrl/events/category'; // Append '/{category}' dynamically
|
||||
static const String updateEventStatus = '$baseUrl/events'; // Append '/{id}/status' dynamically
|
||||
static const String searchEvents = '$baseUrl/events/search'; // Use query parameter for 'keyword'
|
||||
static const String getEventsByUser = '$baseUrl/events/user'; // Append '/{userId}' dynamically
|
||||
static const String getEventsByStatus = '$baseUrl/events/status'; // Append '/{status}' dynamically
|
||||
static const String getEventsBetweenDates = '$baseUrl/events/between-dates'; // Use query parameters for startDate and endDate
|
||||
|
||||
// Other URLs can be added here as the project expands
|
||||
}
|
||||
|
||||
@@ -27,3 +27,26 @@ class ServerExceptionWithMessage implements Exception {
|
||||
String toString() => 'ServerException: $message';
|
||||
}
|
||||
|
||||
class UserNotFoundException implements Exception {
|
||||
final String message;
|
||||
UserNotFoundException([this.message = "User not found"]);
|
||||
|
||||
@override
|
||||
String toString() => "UserNotFoundException: $message";
|
||||
}
|
||||
|
||||
class ConflictException implements Exception {
|
||||
final String message;
|
||||
ConflictException([this.message = "Conflict"]);
|
||||
|
||||
@override
|
||||
String toString() => "ConflictException: $message";
|
||||
}
|
||||
|
||||
class UnauthorizedException implements Exception {
|
||||
final String message;
|
||||
UnauthorizedException([this.message = "Unauthorized"]);
|
||||
|
||||
@override
|
||||
String toString() => "UnauthorizedException: $message";
|
||||
}
|
||||
@@ -1,20 +1,116 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:afterwork/core/constants/colors.dart';
|
||||
|
||||
/// Classe qui définit les thèmes de l'application AfterWork.
|
||||
/// Elle gère à la fois le thème clair et le thème sombre, avec des personnalisations
|
||||
/// pour les couleurs, les boutons, les textes et d'autres éléments visuels.
|
||||
class AppTheme {
|
||||
/// Thème clair
|
||||
static final ThemeData lightTheme = ThemeData(
|
||||
primaryColor: Colors.blue,
|
||||
colorScheme: const ColorScheme.light(
|
||||
secondary: Colors.orange,
|
||||
),
|
||||
brightness: Brightness.light,
|
||||
buttonTheme: const ButtonThemeData(buttonColor: Colors.blue),
|
||||
primaryColor: AppColors.lightPrimary,
|
||||
scaffoldBackgroundColor: AppColors.lightBackground,
|
||||
appBarTheme: const AppBarTheme(
|
||||
color: AppColors.lightPrimary,
|
||||
iconTheme: IconThemeData(color: AppColors.lightOnPrimary),
|
||||
),
|
||||
iconTheme: const IconThemeData(color: AppColors.lightTextPrimary),
|
||||
colorScheme: const ColorScheme.light(
|
||||
primary: AppColors.lightPrimary,
|
||||
secondary: AppColors.lightSecondary,
|
||||
onPrimary: AppColors.lightOnPrimary,
|
||||
onSecondary: AppColors.lightOnSecondary,
|
||||
surface: AppColors.lightSurface,
|
||||
),
|
||||
buttonTheme: const ButtonThemeData(
|
||||
buttonColor: AppColors.lightPrimary,
|
||||
textTheme: ButtonTextTheme.primary,
|
||||
),
|
||||
textTheme: const TextTheme(
|
||||
bodyLarge: TextStyle(color: AppColors.lightTextPrimary),
|
||||
bodyMedium: TextStyle(color: AppColors.lightTextSecondary),
|
||||
titleLarge: TextStyle(color: AppColors.lightTextPrimary),
|
||||
),
|
||||
inputDecorationTheme: InputDecorationTheme(
|
||||
filled: true,
|
||||
fillColor: AppColors.lightSurface,
|
||||
labelStyle: const TextStyle(color: AppColors.lightTextPrimary),
|
||||
hintStyle: const TextStyle(color: AppColors.lightTextSecondary),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderSide: const BorderSide(color: AppColors.lightPrimary),
|
||||
borderRadius: BorderRadius.circular(12.0),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderSide: const BorderSide(color: Colors.grey),
|
||||
borderRadius: BorderRadius.circular(12.0),
|
||||
),
|
||||
),
|
||||
floatingActionButtonTheme: const FloatingActionButtonThemeData(
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
foregroundColor: AppColors.lightOnPrimary,
|
||||
),
|
||||
elevatedButtonTheme: ElevatedButtonThemeData(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.lightPrimary,
|
||||
foregroundColor: AppColors.lightOnPrimary,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
|
||||
textStyle: const TextStyle(fontSize: 18),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
/// Thème sombre
|
||||
static final ThemeData darkTheme = ThemeData(
|
||||
primaryColor: Colors.black,
|
||||
colorScheme: const ColorScheme.dark(
|
||||
secondary: Colors.red,
|
||||
),
|
||||
brightness: Brightness.dark,
|
||||
primaryColor: AppColors.darkPrimary,
|
||||
scaffoldBackgroundColor: AppColors.darkBackground,
|
||||
appBarTheme: const AppBarTheme(
|
||||
color: AppColors.darkPrimary,
|
||||
iconTheme: IconThemeData(color: AppColors.darkOnPrimary),
|
||||
),
|
||||
iconTheme: const IconThemeData(color: AppColors.darkTextPrimary),
|
||||
colorScheme: const ColorScheme.dark(
|
||||
primary: AppColors.darkPrimary,
|
||||
secondary: AppColors.darkSecondary,
|
||||
onPrimary: AppColors.darkOnPrimary,
|
||||
onSecondary: AppColors.darkOnSecondary,
|
||||
surface: AppColors.darkSurface,
|
||||
),
|
||||
buttonTheme: const ButtonThemeData(
|
||||
buttonColor: AppColors.darkSecondary,
|
||||
textTheme: ButtonTextTheme.primary,
|
||||
),
|
||||
textTheme: const TextTheme(
|
||||
bodyLarge: TextStyle(color: AppColors.darkTextPrimary),
|
||||
bodyMedium: TextStyle(color: AppColors.darkTextSecondary),
|
||||
titleLarge: TextStyle(color: AppColors.darkTextPrimary),
|
||||
),
|
||||
inputDecorationTheme: InputDecorationTheme(
|
||||
filled: true,
|
||||
fillColor: AppColors.darkSurface,
|
||||
labelStyle: const TextStyle(color: AppColors.darkTextPrimary),
|
||||
hintStyle: const TextStyle(color: AppColors.darkTextSecondary),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderSide: const BorderSide(color: AppColors.darkSecondary),
|
||||
borderRadius: BorderRadius.circular(12.0),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderSide: const BorderSide(color: AppColors.darkTextSecondary),
|
||||
borderRadius: BorderRadius.circular(12.0),
|
||||
),
|
||||
),
|
||||
floatingActionButtonTheme: const FloatingActionButtonThemeData(
|
||||
backgroundColor: AppColors.darkSecondary,
|
||||
foregroundColor: AppColors.darkOnPrimary,
|
||||
),
|
||||
elevatedButtonTheme: ElevatedButtonThemeData(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.darkSecondary,
|
||||
foregroundColor: AppColors.darkOnPrimary,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
|
||||
textStyle: const TextStyle(fontSize: 18),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
18
lib/core/theme/theme_provider.dart
Normal file
@@ -0,0 +1,18 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'app_theme.dart'; // Importe tes définitions de thème
|
||||
|
||||
class ThemeProvider with ChangeNotifier {
|
||||
bool _isDarkMode = false; // Mode sombre par défaut désactivé
|
||||
|
||||
bool get isDarkMode => _isDarkMode;
|
||||
|
||||
void toggleTheme() {
|
||||
_isDarkMode = !_isDarkMode;
|
||||
notifyListeners(); // Notifie les widgets dépendants
|
||||
}
|
||||
|
||||
// Utilise AppTheme pour obtenir le thème courant
|
||||
ThemeData get currentTheme {
|
||||
return _isDarkMode ? AppTheme.darkTheme : AppTheme.lightTheme;
|
||||
}
|
||||
}
|
||||
15
lib/core/utils/calculate_time_ago.dart
Normal file
@@ -0,0 +1,15 @@
|
||||
// Fichier utilitaire pour le calcul du temps écoulé
|
||||
String calculateTimeAgo(DateTime publicationDate) {
|
||||
final now = DateTime.now();
|
||||
final difference = now.difference(publicationDate);
|
||||
|
||||
if (difference.inDays > 0) {
|
||||
return '${difference.inDays} jour${difference.inDays > 1 ? 's' : ''}';
|
||||
} else if (difference.inHours > 0) {
|
||||
return '${difference.inHours} heure${difference.inHours > 1 ? 's' : ''}';
|
||||
} else if (difference.inMinutes > 0) {
|
||||
return '${difference.inMinutes} minute${difference.inMinutes > 1 ? 's' : ''}';
|
||||
} else {
|
||||
return 'À l\'instant';
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import 'package:intl/intl.dart';
|
||||
|
||||
class DateFormatter {
|
||||
static String formatDate(DateTime date) {
|
||||
return DateFormat('EEEE dd MMMM yyyy', 'fr_FR').format(date);
|
||||
// Formater la date avec l'heure incluse
|
||||
return DateFormat('EEEE dd MMMM yyyy, à HH:mm', 'fr_FR').format(date);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ class EventRemoteDataSource {
|
||||
print('Création d\'un nouvel événement avec les données: ${event.toJson()}');
|
||||
|
||||
final response = await client.post(
|
||||
Uri.parse(Urls.eventsUrl),
|
||||
Uri.parse(Urls.createEvent),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode(event.toJson()),
|
||||
);
|
||||
@@ -53,7 +53,7 @@ class EventRemoteDataSource {
|
||||
Future<EventModel> getEventById(String id) async {
|
||||
print('Récupération de l\'événement avec l\'ID: $id');
|
||||
|
||||
final response = await client.get(Uri.parse('${Urls.eventsUrl}/$id'));
|
||||
final response = await client.get(Uri.parse('${Urls.getEventById}/$id'));
|
||||
|
||||
print('Statut de la réponse: ${response.statusCode}');
|
||||
|
||||
@@ -71,7 +71,7 @@ class EventRemoteDataSource {
|
||||
print('Mise à jour de l\'événement avec l\'ID: $id, données: ${event.toJson()}');
|
||||
|
||||
final response = await client.put(
|
||||
Uri.parse('${Urls.eventsUrl}/$id'),
|
||||
Uri.parse('${Urls.updateEvent}/$id'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode(event.toJson()),
|
||||
);
|
||||
@@ -91,7 +91,7 @@ class EventRemoteDataSource {
|
||||
Future<void> deleteEvent(String id) async {
|
||||
print('Suppression de l\'événement avec l\'ID: $id');
|
||||
|
||||
final response = await client.delete(Uri.parse('${Urls.eventsUrl}/$id'));
|
||||
final response = await client.delete(Uri.parse('${Urls.deleteEvent}/$id'));
|
||||
|
||||
print('Statut de la réponse: ${response.statusCode}');
|
||||
|
||||
@@ -108,7 +108,7 @@ class EventRemoteDataSource {
|
||||
print('Participation à l\'événement avec l\'ID: $eventId, utilisateur: $userId');
|
||||
|
||||
final response = await client.post(
|
||||
Uri.parse('${Urls.eventsUrl}/$eventId/participate'),
|
||||
Uri.parse('${Urls.addParticipant}/$eventId/participate'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({'userId': userId}),
|
||||
);
|
||||
@@ -129,7 +129,7 @@ class EventRemoteDataSource {
|
||||
print('Réaction à l\'événement avec l\'ID: $eventId, utilisateur: $userId');
|
||||
|
||||
final response = await client.post(
|
||||
Uri.parse('${Urls.eventsUrl}/$eventId/react'),
|
||||
Uri.parse('${Urls.baseUrl}/$eventId/react'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({'userId': userId}),
|
||||
);
|
||||
@@ -149,7 +149,7 @@ class EventRemoteDataSource {
|
||||
print('Fermeture de l\'événement avec l\'ID: $eventId');
|
||||
|
||||
final response = await client.post(
|
||||
Uri.parse('${Urls.eventsUrl}/$eventId/close'),
|
||||
Uri.parse('${Urls.closeEvent}/$eventId/close'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
);
|
||||
|
||||
@@ -174,7 +174,7 @@ class EventRemoteDataSource {
|
||||
print('Réouverture de l\'événement avec l\'ID: $eventId');
|
||||
|
||||
final response = await client.post(
|
||||
Uri.parse('${Urls.eventsUrl}/$eventId/reopen'),
|
||||
Uri.parse('${Urls.baseUrl}/$eventId/reopen'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
);
|
||||
|
||||
@@ -193,4 +193,5 @@ class EventRemoteDataSource {
|
||||
throw ServerExceptionWithMessage('Une erreur est survenue lors de la réouverture de l\'événement.');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,90 +1,141 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:afterwork/core/constants/urls.dart';
|
||||
import 'package:afterwork/data/models/user_model.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../../core/errors/exceptions.dart';
|
||||
|
||||
/// Classe pour gérer les opérations API pour les utilisateurs.
|
||||
/// Chaque action est loguée pour faciliter la traçabilité et le débogage.
|
||||
class UserRemoteDataSource {
|
||||
final http.Client client;
|
||||
|
||||
/// Constructeur avec injection du client HTTP
|
||||
UserRemoteDataSource(this.client);
|
||||
|
||||
// Authentifier l'utilisateur
|
||||
Future<UserModel> authenticateUser(String email, String password, String userId) async {
|
||||
if (email.isEmpty || password.isEmpty) {
|
||||
throw Exception('Email ou mot de passe vide');
|
||||
}
|
||||
/// Authentifie un utilisateur avec l'email et le mot de passe en clair.
|
||||
/// Si l'authentification réussit, retourne un objet `UserModel`.
|
||||
Future<UserModel> authenticateUser(String email, String password) async {
|
||||
print("Tentative d'authentification pour l'email : $email");
|
||||
|
||||
final response = await client.post(
|
||||
Uri.parse('${Urls.baseUrl}/users/authenticate'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({
|
||||
'email': email,
|
||||
'motDePasse': password,
|
||||
}),
|
||||
);
|
||||
try {
|
||||
// Requête POST avec l'email et le mot de passe en clair
|
||||
final response = await client.post(
|
||||
Uri.parse('${Urls.baseUrl}/users/authenticate'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({
|
||||
'email': email,
|
||||
'motDePasse': password, // Le mot de passe est envoyé en clair pour le moment
|
||||
}),
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final jsonResponse = json.decode(response.body);
|
||||
return UserModel.fromJson(jsonResponse);
|
||||
} else if (response.statusCode == 401) {
|
||||
throw AuthenticationException('Email ou mot de passe incorrect');
|
||||
} else {
|
||||
throw ServerException();
|
||||
print("Réponse du serveur pour l'authentification : ${response.statusCode} - ${response.body}");
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
// Si l'authentification réussit, retourne l'utilisateur
|
||||
return UserModel.fromJson(jsonDecode(response.body));
|
||||
} else if (response.statusCode == 401) {
|
||||
// Gestion des erreurs d'authentification
|
||||
throw UnauthorizedException();
|
||||
} else {
|
||||
throw ServerException();
|
||||
}
|
||||
} catch (e) {
|
||||
print("Erreur d'authentification : $e");
|
||||
throw Exception("Erreur lors de l'authentification : $e");
|
||||
}
|
||||
}
|
||||
|
||||
// Récupérer un utilisateur par ID
|
||||
/// Récupère un utilisateur par son identifiant et logue les étapes.
|
||||
Future<UserModel> getUser(String id) async {
|
||||
final response = await client.get(Uri.parse('${Urls.baseUrl}/users/$id'));
|
||||
print("Tentative de récupération de l'utilisateur avec l'ID : $id");
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return UserModel.fromJson(json.decode(response.body));
|
||||
} else {
|
||||
throw ServerException();
|
||||
try {
|
||||
final response = await client.get(Uri.parse('${Urls.baseUrl}/users/$id'));
|
||||
print("Réponse du serveur pour getUser : ${response.statusCode} - ${response.body}");
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return UserModel.fromJson(json.decode(response.body));
|
||||
} else if (response.statusCode == 404) {
|
||||
print("Utilisateur non trouvé.");
|
||||
throw UserNotFoundException();
|
||||
} else {
|
||||
throw ServerException();
|
||||
}
|
||||
} catch (e) {
|
||||
print("Erreur lors de la récupération de l'utilisateur : $e");
|
||||
throw Exception("Erreur lors de la récupération de l'utilisateur : $e");
|
||||
}
|
||||
}
|
||||
|
||||
// Créer un nouvel utilisateur
|
||||
/// Crée un nouvel utilisateur et logue les détails de la requête.
|
||||
Future<UserModel> createUser(UserModel user) async {
|
||||
final response = await client.post(
|
||||
Uri.parse('${Urls.baseUrl}/users'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode(user.toJson()),
|
||||
);
|
||||
print("Création d'un nouvel utilisateur : ${user.toJson()}");
|
||||
|
||||
if (response.statusCode == 201) {
|
||||
return UserModel.fromJson(json.decode(response.body));
|
||||
} else {
|
||||
throw ServerException();
|
||||
try {
|
||||
final response = await client.post(
|
||||
Uri.parse('${Urls.baseUrl}/users'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode(user.toJson()),
|
||||
);
|
||||
print("Réponse du serveur pour createUser : ${response.statusCode} - ${response.body}");
|
||||
|
||||
if (response.statusCode == 201) {
|
||||
return UserModel.fromJson(json.decode(response.body));
|
||||
} else if (response.statusCode == 409) {
|
||||
// Gestion des conflits (utilisateur déjà existant)
|
||||
throw ConflictException();
|
||||
} else {
|
||||
throw ServerException();
|
||||
}
|
||||
} catch (e) {
|
||||
print("Erreur lors de la création de l'utilisateur : $e");
|
||||
throw Exception("Erreur lors de la création de l'utilisateur : $e");
|
||||
}
|
||||
}
|
||||
|
||||
// Mettre à jour un utilisateur
|
||||
/// Met à jour un utilisateur existant et logue les étapes.
|
||||
Future<UserModel> updateUser(UserModel user) async {
|
||||
final response = await client.put(
|
||||
Uri.parse('${Urls.baseUrl}/users/${user.userId}'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode(user.toJson()),
|
||||
);
|
||||
print("Mise à jour de l'utilisateur : ${user.toJson()}");
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return UserModel.fromJson(json.decode(response.body));
|
||||
} else {
|
||||
throw ServerException();
|
||||
try {
|
||||
final response = await client.put(
|
||||
Uri.parse('${Urls.baseUrl}/users/${user.userId}'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode(user.toJson()),
|
||||
);
|
||||
print("Réponse du serveur pour updateUser : ${response.statusCode} - ${response.body}");
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return UserModel.fromJson(json.decode(response.body));
|
||||
} else if (response.statusCode == 404) {
|
||||
// Gestion des cas où l'utilisateur n'est pas trouvé
|
||||
throw UserNotFoundException();
|
||||
} else {
|
||||
throw ServerException();
|
||||
}
|
||||
} catch (e) {
|
||||
print("Erreur lors de la mise à jour de l'utilisateur : $e");
|
||||
throw Exception("Erreur lors de la mise à jour de l'utilisateur : $e");
|
||||
}
|
||||
}
|
||||
|
||||
// Supprimer un utilisateur par ID
|
||||
/// Supprime un utilisateur et logue chaque étape.
|
||||
Future<void> deleteUser(String id) async {
|
||||
final response = await client.delete(
|
||||
Uri.parse('${Urls.baseUrl}/users/$id'),
|
||||
);
|
||||
print("Tentative de suppression de l'utilisateur avec l'ID : $id");
|
||||
|
||||
if (response.statusCode != 204) {
|
||||
throw ServerException();
|
||||
try {
|
||||
final response = await client.delete(Uri.parse('${Urls.baseUrl}/users/$id'));
|
||||
print("Réponse du serveur pour deleteUser : ${response.statusCode} - ${response.body}");
|
||||
|
||||
if (response.statusCode != 204) {
|
||||
print("Erreur lors de la suppression de l'utilisateur.");
|
||||
throw ServerException();
|
||||
} else {
|
||||
print("Utilisateur supprimé avec succès.");
|
||||
}
|
||||
} catch (e) {
|
||||
print("Erreur lors de la suppression de l'utilisateur : $e");
|
||||
throw Exception("Erreur lors de la suppression de l'utilisateur : $e");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,78 +1,71 @@
|
||||
import 'package:afterwork/data/models/user_model.dart';
|
||||
|
||||
/// Modèle de données représentant un événement.
|
||||
/// Cette classe encapsule toutes les propriétés d'un événement, y compris
|
||||
/// le titre, la description, la date, la localisation, la catégorie, les liens,
|
||||
/// l'image, le créateur, les participants et le statut de l'événement.
|
||||
class EventModel {
|
||||
final String id; // Identifiant unique de l'événement
|
||||
final String title; // Titre de l'événement
|
||||
final String description; // Description de l'événement
|
||||
final String date; // Date de l'événement
|
||||
final String location; // Localisation de l'événement
|
||||
final String category; // Catégorie de l'événement
|
||||
final String link; // Lien associé à l'événement
|
||||
final String? imageUrl; // URL de l'image de l'événement (optionnel)
|
||||
final UserModel creator; // Créateur de l'événement
|
||||
final List<UserModel> participants; // Liste des participants à l'événement
|
||||
final String status; // Statut de l'événement (e.g., "OPEN", "CLOSED")
|
||||
final String id;
|
||||
final String title;
|
||||
final String description;
|
||||
final String startDate; // Utiliser startDate au lieu de date, si c'est ce que l'API retourne
|
||||
final String location;
|
||||
final String category;
|
||||
final String link;
|
||||
final String? imageUrl; // Nullable
|
||||
final String creatorEmail; // Remplacer UserModel si le créateur est un email
|
||||
final List<dynamic> participants; // Si participants est une liste simple
|
||||
final String status;
|
||||
final int reactionsCount;
|
||||
final int commentsCount;
|
||||
final int sharesCount;
|
||||
|
||||
/// Constructeur pour initialiser toutes les propriétés de l'événement.
|
||||
EventModel({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.description,
|
||||
required this.date,
|
||||
required this.startDate,
|
||||
required this.location,
|
||||
required this.category,
|
||||
required this.link,
|
||||
this.imageUrl,
|
||||
required this.creator,
|
||||
required this.creatorEmail,
|
||||
required this.participants,
|
||||
required this.status,
|
||||
required this.reactionsCount,
|
||||
required this.commentsCount,
|
||||
required this.sharesCount,
|
||||
});
|
||||
|
||||
/// Convertit un objet JSON en `EventModel`.
|
||||
factory EventModel.fromJson(Map<String, dynamic> json) {
|
||||
// Log de la conversion depuis JSON
|
||||
print('Conversion de l\'objet JSON en EventModel: ${json['id']}');
|
||||
|
||||
return EventModel(
|
||||
id: json['id'],
|
||||
title: json['title'],
|
||||
description: json['description'],
|
||||
date: json['date'],
|
||||
startDate: json['startDate'], // Vérifier si c'est bien startDate
|
||||
location: json['location'],
|
||||
category: json['category'],
|
||||
link: json['link'] ?? '', // Assure qu'il ne soit pas null
|
||||
imageUrl: json['imageUrl'] ?? '', // Assure qu'il ne soit pas null
|
||||
status: json['status'],
|
||||
creator: UserModel.fromJson(json['creator']),
|
||||
participants: json['participants'] != null
|
||||
? (json['participants'] as List)
|
||||
.map((user) => UserModel.fromJson(user))
|
||||
.toList()
|
||||
: [], // Si participants est null, retourne une liste vide
|
||||
link: json['link'] ?? '',
|
||||
imageUrl: json['imageUrl'], // Peut être null
|
||||
creatorEmail: json['creatorEmail'], // Email du créateur
|
||||
participants: json['participants'] ?? [], // Gérer les participants
|
||||
status: json['status'] ?? 'open', // Par défaut à "open" si non fourni
|
||||
reactionsCount: json['reactionsCount'] ?? 0,
|
||||
commentsCount: json['commentsCount'] ?? 0,
|
||||
sharesCount: json['sharesCount'] ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
/// Convertit un `EventModel` en objet JSON.
|
||||
Map<String, dynamic> toJson() {
|
||||
// Log de la conversion en JSON
|
||||
print('Conversion de l\'EventModel en objet JSON: $id');
|
||||
|
||||
return {
|
||||
'id': id,
|
||||
'title': title,
|
||||
'description': description,
|
||||
'date': date,
|
||||
'startDate': startDate,
|
||||
'location': location,
|
||||
'category': category,
|
||||
'link': link,
|
||||
'imageUrl': imageUrl,
|
||||
'creator': creator.toJson(),
|
||||
'participants': participants.map((user) => user.toJson()).toList(),
|
||||
'creatorEmail': creatorEmail,
|
||||
'participants': participants,
|
||||
'status': status,
|
||||
'reactionsCount': reactionsCount,
|
||||
'commentsCount': commentsCount,
|
||||
'sharesCount': sharesCount,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import 'package:afterwork/domain/entities/user.dart';
|
||||
import '../../domain/entities/user.dart';
|
||||
|
||||
class UserModel extends User {
|
||||
const UserModel({
|
||||
required String userId, // Utilisez `id` pour correspondre à l'entité User
|
||||
/// Modèle représentant l'utilisateur dans l'application AfterWork.
|
||||
/// Ce modèle est utilisé pour la conversion JSON et l'interaction avec l'API.
|
||||
class UserModel extends User {
|
||||
UserModel({
|
||||
required String userId,
|
||||
required String nom,
|
||||
required String prenoms,
|
||||
required String email,
|
||||
@@ -15,23 +17,25 @@ class UserModel extends User {
|
||||
motDePasse: motDePasse,
|
||||
);
|
||||
|
||||
/// Factory pour créer un `UserModel` à partir d'un JSON reçu depuis l'API.
|
||||
factory UserModel.fromJson(Map<String, dynamic> json) {
|
||||
return UserModel(
|
||||
userId: json['id'] ?? '',
|
||||
nom: json['nom'] ?? '',
|
||||
prenoms: json['prenoms'] ?? '',
|
||||
email: json['email'] ?? '',
|
||||
nom: json['nom'] ?? 'Inconnu',
|
||||
prenoms: json['prenoms'] ?? 'Inconnu',
|
||||
email: json['email'] ?? 'inconnu@example.com',
|
||||
motDePasse: json['motDePasse'] ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
/// Convertit le `UserModel` en JSON pour l'envoi vers l'API.
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': userId, // Utilisez `id` pour correspondre à l'entité User
|
||||
'id': userId,
|
||||
'nom': nom,
|
||||
'prenoms': prenoms,
|
||||
'email': email,
|
||||
'motDePasse': motDePasse,
|
||||
'motDePasse': motDePasse, // Mot de passe en clair (comme demandé temporairement)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,49 @@
|
||||
import 'package:afterwork/domain/entities/user.dart';
|
||||
import 'package:afterwork/domain/repositories/user_repository.dart';
|
||||
import 'dart:convert';
|
||||
import 'package:afterwork/data/datasources/user_remote_data_source.dart';
|
||||
import 'package:afterwork/data/models/user_model.dart';
|
||||
import 'package:afterwork/domain/entities/user.dart';
|
||||
import 'package:afterwork/domain/repositories/user_repository.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../../core/constants/urls.dart';
|
||||
|
||||
/// Implémentation du repository des utilisateurs.
|
||||
/// Cette classe fait le lien entre les appels de l'application et les services distants pour les opérations sur les utilisateurs.
|
||||
class UserRepositoryImpl implements UserRepository {
|
||||
final UserRemoteDataSource remoteDataSource;
|
||||
|
||||
/// Constructeur avec injection de la source de données distante.
|
||||
UserRepositoryImpl({required this.remoteDataSource});
|
||||
|
||||
/// Récupère un utilisateur par son ID depuis la source de données distante.
|
||||
@override
|
||||
Future<User> getUser(String id) async {
|
||||
UserModel userModel = await remoteDataSource.getUser(id);
|
||||
return userModel; // Retourne un UserModel qui est un sous-type de User
|
||||
return userModel; // Retourne un UserModel qui est un sous-type de User.
|
||||
}
|
||||
|
||||
Future<User> authenticateUser(String email, String password, String userId) async {
|
||||
UserModel userModel = await remoteDataSource.authenticateUser(email, password, userId);
|
||||
return userModel; // Retourne un UserModel qui est un sous-type de User
|
||||
/// Authentifie un utilisateur par email et mot de passe (en clair, temporairement).
|
||||
Future<UserModel> authenticateUser(String email, String password) async {
|
||||
print("Tentative d'authentification pour l'email : $email");
|
||||
|
||||
try {
|
||||
// Requête POST avec les identifiants utilisateur pour l'authentification
|
||||
final response = await http.post(
|
||||
Uri.parse('${Urls.baseUrl}/users/authenticate'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({'email': email, 'motDePasse': password}),
|
||||
);
|
||||
|
||||
print("Réponse du serveur pour l'authentification : ${response.statusCode} - ${response.body}");
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return UserModel.fromJson(jsonDecode(response.body));
|
||||
} else {
|
||||
throw Exception("Erreur lors de l'authentification : ${response.statusCode}");
|
||||
}
|
||||
} catch (e) {
|
||||
print("Erreur d'authentification : $e");
|
||||
throw Exception("Erreur lors de l'authentification : $e");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import 'dart:convert';
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
String hashPassword(String password) {
|
||||
var bytes = utf8.encode(password); // Convertir en bytes
|
||||
var digest = sha256.convert(bytes); // Hachage SHA-256
|
||||
return digest.toString(); // Retourner le hash sous forme de chaîne
|
||||
}
|
||||
47
lib/data/services/hash_password_service.dart
Normal file
@@ -0,0 +1,47 @@
|
||||
import 'package:flutter_bcrypt/flutter_bcrypt.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:afterwork/core/constants/urls.dart';
|
||||
|
||||
class HashPasswordService {
|
||||
/// Hache le mot de passe en utilisant Bcrypt.
|
||||
/// Renvoie une chaîne hachée sécurisée.
|
||||
Future<String> hashPassword(String email, String password) async {
|
||||
try {
|
||||
print("Tentative de récupération du sel depuis le serveur pour l'email : $email");
|
||||
|
||||
// Récupérer le sel depuis le serveur avec l'email
|
||||
final response = await http.get(Uri.parse('${Urls.baseUrl}/users/salt?email=$email'));
|
||||
|
||||
String salt;
|
||||
if (response.statusCode == 200 && response.body.isNotEmpty) {
|
||||
salt = response.body;
|
||||
print("Sel récupéré depuis le serveur : $salt");
|
||||
} else {
|
||||
// Si le sel n'est pas trouvé, on en génère un
|
||||
salt = await FlutterBcrypt.saltWithRounds(rounds: 12);
|
||||
print("Sel généré : $salt");
|
||||
}
|
||||
|
||||
// Hachage du mot de passe avec le sel
|
||||
String hashedPassword = await FlutterBcrypt.hashPw(password: password, salt: salt);
|
||||
print("Mot de passe haché avec succès : $hashedPassword");
|
||||
return hashedPassword;
|
||||
} catch (e) {
|
||||
print("Erreur lors du hachage du mot de passe : $e");
|
||||
throw Exception("Erreur lors du hachage du mot de passe.");
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> verifyPassword(String password, String hashedPassword) async {
|
||||
try {
|
||||
print("Début de la vérification du mot de passe");
|
||||
bool result = await FlutterBcrypt.verify(password: password, hash: hashedPassword);
|
||||
print("Résultat de la vérification : $result");
|
||||
return result;
|
||||
} catch (e) {
|
||||
print("Erreur lors de la vérification du mot de passe : $e");
|
||||
throw Exception("Erreur lors de la vérification du mot de passe.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,50 +1,82 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// Classe pour gérer les préférences utilisateur à l'aide de SharedPreferences.
|
||||
/// Permet de stocker et récupérer des informations de manière non sécurisée,
|
||||
/// contrairement au stockage sécurisé qui est utilisé pour des données sensibles.
|
||||
class PreferencesHelper {
|
||||
// Initialisation de SharedPreferences en tant que Future
|
||||
final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
|
||||
|
||||
/// Sauvegarde une chaîne de caractères (String) dans les préférences.
|
||||
Future<void> setString(String key, String value) async {
|
||||
print("Sauvegarde dans les préférences : clé = $key, valeur = $value");
|
||||
final prefs = await _prefs;
|
||||
await prefs.setString(key, value);
|
||||
print("Sauvegarde réussie pour la clé : $key");
|
||||
}
|
||||
|
||||
/// Récupère une chaîne de caractères depuis les préférences.
|
||||
Future<String?> getString(String key) async {
|
||||
print("Récupération depuis les préférences pour la clé : $key");
|
||||
final prefs = await _prefs;
|
||||
return prefs.getString(key);
|
||||
final value = prefs.getString(key);
|
||||
print("Valeur récupérée pour la clé $key : $value");
|
||||
return value;
|
||||
}
|
||||
|
||||
/// Supprime une entrée dans les préférences.
|
||||
Future<void> remove(String key) async {
|
||||
print("Suppression dans les préférences pour la clé : $key");
|
||||
final prefs = await _prefs;
|
||||
await prefs.remove(key);
|
||||
print("Suppression réussie pour la clé : $key");
|
||||
}
|
||||
|
||||
/// Sauvegarde l'identifiant utilisateur dans les préférences.
|
||||
Future<void> saveUserId(String userId) async {
|
||||
print("Sauvegarde de l'userId dans les préférences : $userId");
|
||||
await setString('user_id', userId);
|
||||
print("Sauvegarde réussie de l'userId.");
|
||||
}
|
||||
|
||||
/// Récupère l'identifiant utilisateur depuis les préférences.
|
||||
Future<String?> getUserId() async {
|
||||
print("Récupération de l'userId depuis les préférences.");
|
||||
return await getString('user_id');
|
||||
}
|
||||
|
||||
/// Sauvegarde le nom d'utilisateur dans les préférences.
|
||||
Future<void> saveUserName(String userName) async {
|
||||
print("Sauvegarde du userName dans les préférences : $userName");
|
||||
await setString('user_name', userName);
|
||||
print("Sauvegarde réussie du userName.");
|
||||
}
|
||||
|
||||
/// Récupère le nom d'utilisateur depuis les préférences.
|
||||
Future<String?> getUserName() async {
|
||||
print("Récupération du userName depuis les préférences.");
|
||||
return await getString('user_name');
|
||||
}
|
||||
|
||||
/// Sauvegarde le prénom de l'utilisateur dans les préférences.
|
||||
Future<void> saveUserLastName(String userLastName) async {
|
||||
print("Sauvegarde du userLastName dans les préférences : $userLastName");
|
||||
await setString('user_last_name', userLastName);
|
||||
print("Sauvegarde réussie du userLastName.");
|
||||
}
|
||||
|
||||
/// Récupère le prénom de l'utilisateur depuis les préférences.
|
||||
Future<String?> getUserLastName() async {
|
||||
print("Récupération du userLastName depuis les préférences.");
|
||||
return await getString('user_last_name');
|
||||
}
|
||||
|
||||
/// Supprime toutes les informations utilisateur dans les préférences.
|
||||
Future<void> clearUserInfo() async {
|
||||
print("Suppression des informations utilisateur (userId, userName, userLastName) des préférences.");
|
||||
await remove('user_id');
|
||||
await remove('user_name');
|
||||
await remove('user_last_name');
|
||||
print("Suppression réussie des informations utilisateur.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,47 +1,78 @@
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
|
||||
/// Classe pour gérer le stockage sécurisé dans l'application.
|
||||
/// Utilise FlutterSecureStorage pour stocker, lire et supprimer des données sensibles.
|
||||
class SecureStorage {
|
||||
// Instance de FlutterSecureStorage pour gérer le stockage sécurisé
|
||||
final FlutterSecureStorage _storage = const FlutterSecureStorage();
|
||||
|
||||
/// Écrit une valeur dans le stockage sécurisé avec la clé spécifiée.
|
||||
Future<void> write(String key, String value) async {
|
||||
print("Écriture dans le stockage sécurisé : clé = $key, valeur = $value");
|
||||
await _storage.write(key: key, value: value);
|
||||
print("Écriture réussie pour la clé : $key");
|
||||
}
|
||||
|
||||
/// Lit une valeur depuis le stockage sécurisé en fonction de la clé spécifiée.
|
||||
Future<String?> read(String key) async {
|
||||
return await _storage.read(key: key);
|
||||
print("Lecture dans le stockage sécurisé pour la clé : $key");
|
||||
final value = await _storage.read(key: key);
|
||||
print("Valeur lue pour la clé $key : $value");
|
||||
return value;
|
||||
}
|
||||
|
||||
/// Supprime une entrée dans le stockage sécurisé pour la clé spécifiée.
|
||||
Future<void> delete(String key) async {
|
||||
print("Suppression dans le stockage sécurisé pour la clé : $key");
|
||||
await _storage.delete(key: key);
|
||||
print("Suppression réussie pour la clé : $key");
|
||||
}
|
||||
|
||||
/// Sauvegarde l'identifiant utilisateur dans le stockage sécurisé.
|
||||
Future<void> saveUserId(String userId) async {
|
||||
print("Sauvegarde de l'userId dans le stockage sécurisé : $userId");
|
||||
await write('user_id', userId);
|
||||
print("Sauvegarde réussie de l'userId.");
|
||||
}
|
||||
|
||||
/// Récupère l'identifiant utilisateur depuis le stockage sécurisé.
|
||||
Future<String?> getUserId() async {
|
||||
print("Récupération de l'userId depuis le stockage sécurisé.");
|
||||
return await read('user_id');
|
||||
}
|
||||
|
||||
/// Sauvegarde le nom d'utilisateur dans le stockage sécurisé.
|
||||
Future<void> saveUserName(String userName) async {
|
||||
print("Sauvegarde du userName dans le stockage sécurisé : $userName");
|
||||
await write('user_name', userName);
|
||||
print("Sauvegarde réussie du userName.");
|
||||
}
|
||||
|
||||
/// Récupère le nom d'utilisateur depuis le stockage sécurisé.
|
||||
Future<String?> getUserName() async {
|
||||
print("Récupération du userName depuis le stockage sécurisé.");
|
||||
return await read('user_name');
|
||||
}
|
||||
|
||||
/// Sauvegarde le prénom de l'utilisateur dans le stockage sécurisé.
|
||||
Future<void> saveUserLastName(String userLastName) async {
|
||||
print("Sauvegarde du userLastName dans le stockage sécurisé : $userLastName");
|
||||
await write('user_last_name', userLastName);
|
||||
print("Sauvegarde réussie du userLastName.");
|
||||
}
|
||||
|
||||
/// Récupère le prénom de l'utilisateur depuis le stockage sécurisé.
|
||||
Future<String?> getUserLastName() async {
|
||||
print("Récupération du userLastName depuis le stockage sécurisé.");
|
||||
return await read('user_last_name');
|
||||
}
|
||||
|
||||
/// Supprime toutes les informations utilisateur du stockage sécurisé.
|
||||
Future<void> deleteUserInfo() async {
|
||||
print("Suppression des informations utilisateur (userId, userName, userLastName).");
|
||||
await delete('user_id');
|
||||
await delete('user_name');
|
||||
await delete('user_last_name');
|
||||
print("Suppression réussie des informations utilisateur.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import 'package:afterwork/domain/entities/user.dart';
|
||||
|
||||
/// Interface pour le dépôt de l'utilisateur.
|
||||
/// Cette interface définit les contrats que doit respecter tout dépôt
|
||||
/// qui gère les données relatives aux utilisateurs.
|
||||
abstract class UserRepository {
|
||||
Future<User> getUser(String id);
|
||||
/// Méthode pour récupérer un utilisateur par son identifiant.
|
||||
/// Cette méthode retourne un objet [User] ou lève une exception en cas d'échec.
|
||||
Future<User> getUser(String id) {
|
||||
print("Appel à la méthode getUser avec l'ID : $id");
|
||||
throw UnimplementedError("Cette méthode doit être implémentée dans une classe concrète.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,16 +3,28 @@ import 'package:afterwork/domain/entities/user.dart';
|
||||
import 'package:afterwork/domain/repositories/user_repository.dart';
|
||||
import 'package:afterwork/core/errors/failures.dart';
|
||||
|
||||
/// Classe qui implémente le cas d'utilisation permettant de récupérer un utilisateur par son ID.
|
||||
/// Elle interagit avec le dépôt d'utilisateur pour récupérer les données utilisateur.
|
||||
class GetUser {
|
||||
final UserRepository repository;
|
||||
final UserRepository repository; // Référence au dépôt d'utilisateur
|
||||
|
||||
GetUser(this.repository);
|
||||
/// Constructeur qui prend en paramètre un dépôt d'utilisateur.
|
||||
GetUser(this.repository) {
|
||||
print("Initialisation de GetUser avec le UserRepository.");
|
||||
}
|
||||
|
||||
/// Méthode pour récupérer un utilisateur par son ID.
|
||||
/// Retourne soit un [User], soit une [Failure] en cas d'erreur.
|
||||
Future<Either<Failure, User>> call(String id) async {
|
||||
print("Appel à GetUser avec l'ID : $id");
|
||||
|
||||
try {
|
||||
// Appel au dépôt pour récupérer l'utilisateur
|
||||
final user = await repository.getUser(id);
|
||||
print("Utilisateur récupéré avec succès : ${user.userId}");
|
||||
return Right(user);
|
||||
} catch (e) {
|
||||
print("Erreur lors de la récupération de l'utilisateur : $e");
|
||||
return Left(ServerFailure());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,32 +1,35 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:afterwork/config/router.dart';
|
||||
import 'package:afterwork/data/datasources/event_remote_data_source.dart';
|
||||
import 'package:afterwork/data/providers/user_provider.dart';
|
||||
import 'package:afterwork/data/services/preferences_helper.dart';
|
||||
import 'package:afterwork/data/services/secure_storage.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:afterwork/presentation/state_management/event_bloc.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:intl/date_symbol_data_local.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import 'core/theme/theme_provider.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
// Initialisez le formatage de la date pour la locale française
|
||||
// Initialisation du format de date en français
|
||||
await initializeDateFormatting('fr_FR', null);
|
||||
|
||||
// Initialisation des services nécessaires
|
||||
final eventRemoteDataSource = EventRemoteDataSource(http.Client());
|
||||
|
||||
// Remplacez ici par l'utilisation du stockage sécurisé ou des préférences
|
||||
final SecureStorage secureStorage = SecureStorage();
|
||||
final PreferencesHelper preferencesHelper = PreferencesHelper();
|
||||
|
||||
// Récupération des informations stockées
|
||||
String? userId = await secureStorage.getUserId();
|
||||
String? userName = await preferencesHelper.getUserName();
|
||||
String? userLastName = await preferencesHelper.getUserLastName();
|
||||
|
||||
// Si les valeurs sont nulles, vous pouvez définir des valeurs par défaut ou gérer autrement
|
||||
userId ??=
|
||||
'default_user_id'; // Remplacer par une valeur par défaut si nécessaire
|
||||
// Gestion des valeurs par défaut si nécessaires
|
||||
userId ??= 'default_user_id';
|
||||
userName ??= 'Default';
|
||||
userLastName ??= 'User';
|
||||
|
||||
@@ -57,23 +60,29 @@ class MyApp extends StatelessWidget {
|
||||
return MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider(
|
||||
create: (_) =>
|
||||
UserProvider()..setUser(userId, userName, userLastName),
|
||||
create: (_) => UserProvider()..setUser(userId, userName, userLastName),
|
||||
),
|
||||
ChangeNotifierProvider(
|
||||
create: (_) => ThemeProvider(), // Fournisseur de thème
|
||||
),
|
||||
BlocProvider(
|
||||
create: (context) => EventBloc(remoteDataSource: eventRemoteDataSource),
|
||||
),
|
||||
// Ajouter d'autres providers ici si nécessaire
|
||||
],
|
||||
child: MaterialApp(
|
||||
title: 'AfterWork',
|
||||
theme: ThemeData(
|
||||
primarySwatch: Colors.blue,
|
||||
),
|
||||
onGenerateRoute: AppRouter(
|
||||
eventRemoteDataSource: eventRemoteDataSource,
|
||||
userId: userId,
|
||||
userName: userName,
|
||||
userLastName: userLastName,
|
||||
).generateRoute,
|
||||
initialRoute: '/',
|
||||
child: Consumer<ThemeProvider>(
|
||||
builder: (context, themeProvider, _) {
|
||||
return MaterialApp(
|
||||
title: 'AfterWork',
|
||||
theme: themeProvider.currentTheme,
|
||||
onGenerateRoute: AppRouter(
|
||||
eventRemoteDataSource: eventRemoteDataSource,
|
||||
userId: userId,
|
||||
userName: userName,
|
||||
userLastName: userLastName,
|
||||
).generateRoute,
|
||||
initialRoute: '/',
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,38 +1,39 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Écran de gestion des réservations.
|
||||
/// Cet écran permet à l'utilisateur de consulter ses réservations.
|
||||
/// Les logs permettent de tracer les actions de navigation et d'affichage.
|
||||
class ReservationsScreen extends StatelessWidget {
|
||||
const ReservationsScreen({super.key});
|
||||
const ReservationsScreen({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
print("Affichage de l'écran des réservations.");
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Réservations'),
|
||||
backgroundColor: Colors.black,
|
||||
elevation: 0,
|
||||
backgroundColor: Colors.blueAccent,
|
||||
),
|
||||
body: ListView(
|
||||
children: [
|
||||
ListTile(
|
||||
leading: const Icon(Icons.event, color: Colors.blueAccent),
|
||||
title: const Text('Réservation 1', style: TextStyle(color: Colors.white)),
|
||||
subtitle: const Text('Détails de la réservation 1', style: TextStyle(color: Colors.white70)),
|
||||
onTap: () {
|
||||
// Logique pour afficher les détails de la réservation 1
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.event, color: Colors.blueAccent),
|
||||
title: const Text('Réservation 2', style: TextStyle(color: Colors.white)),
|
||||
subtitle: const Text('Détails de la réservation 2', style: TextStyle(color: Colors.white70)),
|
||||
onTap: () {
|
||||
// Logique pour afficher les détails de la réservation 2
|
||||
},
|
||||
),
|
||||
// Ajoutez d'autres ListTile pour les autres réservations
|
||||
],
|
||||
body: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Text(
|
||||
'Aucune réservation trouvée',
|
||||
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
print("L'utilisateur a appuyé sur le bouton 'Ajouter une réservation'.");
|
||||
// Logique pour ajouter une réservation
|
||||
},
|
||||
child: const Text('Ajouter une réservation'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
backgroundColor: Colors.black,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,443 +1,110 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:afterwork/data/models/event_model.dart';
|
||||
import 'package:afterwork/data/models/user_model.dart';
|
||||
import 'package:afterwork/core/constants/urls.dart';
|
||||
import 'package:afterwork/data/services/category_service.dart';
|
||||
import '../location/location_picker_screen.dart';
|
||||
import 'dart:convert';
|
||||
import 'package:fluttertoast/fluttertoast.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
/// Classe représentant la boîte de dialogue pour ajouter un nouvel événement.
|
||||
/// Dialogue pour ajouter un nouvel événement.
|
||||
/// Ce widget affiche un formulaire permettant à l'utilisateur de saisir les détails d'un événement.
|
||||
/// Les logs permettent de suivre les actions de l'utilisateur dans ce dialogue.
|
||||
class AddEventDialog extends StatefulWidget {
|
||||
final String userId;
|
||||
final String userName;
|
||||
final String userLastName;
|
||||
|
||||
const AddEventDialog({
|
||||
super.key,
|
||||
Key? key,
|
||||
required this.userId,
|
||||
required this.userName,
|
||||
required this.userLastName,
|
||||
});
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
_AddEventDialogState createState() => _AddEventDialogState();
|
||||
}
|
||||
|
||||
class _AddEventDialogState extends State<AddEventDialog> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
// Variables pour stocker les données de l'événement
|
||||
String _title = '';
|
||||
String _description = '';
|
||||
DateTime? _selectedDate;
|
||||
String? _imagePath;
|
||||
String _location = 'Abidjan';
|
||||
String _category = '';
|
||||
String _link = '';
|
||||
LatLng? _selectedLatLng = const LatLng(5.348722, -3.985038);
|
||||
Map<String, List<String>> _categories = {};
|
||||
List<String> _currentCategories = [];
|
||||
String? _selectedCategoryType;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadCategories();
|
||||
}
|
||||
|
||||
void _loadCategories() async {
|
||||
final CategoryService categoryService = CategoryService();
|
||||
final categories = await categoryService.loadCategories();
|
||||
setState(() {
|
||||
_categories = categories;
|
||||
_selectedCategoryType = categories.keys.first;
|
||||
_currentCategories = categories[_selectedCategoryType] ?? [];
|
||||
});
|
||||
}
|
||||
final _formKey = GlobalKey<FormState>(); // Clé pour valider le formulaire
|
||||
String _eventName = ''; // Nom de l'événement
|
||||
DateTime _selectedDate = DateTime.now(); // Date de l'événement
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Dialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(15.0),
|
||||
),
|
||||
backgroundColor: const Color(0xFF2C2C3E),
|
||||
child: SingleChildScrollView(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_buildTitleField(),
|
||||
const SizedBox(height: 10),
|
||||
_buildDescriptionField(),
|
||||
const SizedBox(height: 10),
|
||||
_buildDatePicker(),
|
||||
const SizedBox(height: 10),
|
||||
_buildLocationField(context),
|
||||
const SizedBox(height: 10),
|
||||
_buildCategoryField(),
|
||||
const SizedBox(height: 10),
|
||||
_buildImagePicker(),
|
||||
const SizedBox(height: 10),
|
||||
_buildLinkField(),
|
||||
const SizedBox(height: 20),
|
||||
_buildSubmitButton(),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
print("Affichage du dialogue d'ajout d'événement.");
|
||||
|
||||
Widget _buildTitleField() {
|
||||
return TextFormField(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Titre',
|
||||
labelStyle: const TextStyle(color: Colors.white70),
|
||||
filled: true,
|
||||
fillColor: Colors.white.withOpacity(0.1),
|
||||
border: const OutlineInputBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(10.0)),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
prefixIcon: const Icon(Icons.title, color: Colors.white70),
|
||||
),
|
||||
style: const TextStyle(color: Colors.white),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
print('Erreur: Titre est vide');
|
||||
return 'Veuillez entrer un titre';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
onSaved: (value) {
|
||||
_title = value ?? '';
|
||||
print('Titre sauvegardé: $_title');
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDescriptionField() {
|
||||
return TextFormField(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Description',
|
||||
labelStyle: const TextStyle(color: Colors.white70),
|
||||
filled: true,
|
||||
fillColor: Colors.white.withOpacity(0.1),
|
||||
border: const OutlineInputBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(10.0)),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
prefixIcon: const Icon(Icons.description, color: Colors.white70),
|
||||
),
|
||||
style: const TextStyle(color: Colors.white),
|
||||
maxLines: 3,
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
print('Erreur: Description est vide');
|
||||
return 'Veuillez entrer une description';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
onSaved: (value) {
|
||||
_description = value ?? '';
|
||||
print('Description sauvegardée: $_description');
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDatePicker() {
|
||||
return GestureDetector(
|
||||
onTap: () async {
|
||||
final DateTime? picked = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: DateTime.now(),
|
||||
firstDate: DateTime.now(),
|
||||
lastDate: DateTime(2101),
|
||||
);
|
||||
if (picked != null && picked != _selectedDate) {
|
||||
setState(() {
|
||||
_selectedDate = picked;
|
||||
print('Date sélectionnée: $_selectedDate');
|
||||
});
|
||||
} else {
|
||||
print('Date non sélectionnée ou égale à la précédente');
|
||||
}
|
||||
},
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(10.0),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
return AlertDialog(
|
||||
title: const Text('Ajouter un événement'),
|
||||
content: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
_selectedDate == null
|
||||
? 'Sélectionnez une date'
|
||||
: '${_selectedDate!.day}/${_selectedDate!.month}/${_selectedDate!.year}',
|
||||
style: const TextStyle(color: Colors.white70),
|
||||
// Champ pour entrer le nom de l'événement
|
||||
TextFormField(
|
||||
decoration: const InputDecoration(labelText: 'Nom de l\'événement'),
|
||||
onSaved: (value) {
|
||||
_eventName = value ?? '';
|
||||
print("Nom de l'événement saisi : $_eventName");
|
||||
},
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
print("Erreur : le champ du nom de l'événement est vide.");
|
||||
return 'Veuillez entrer un nom d\'événement';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
// Sélecteur de date pour l'événement
|
||||
ElevatedButton(
|
||||
onPressed: () async {
|
||||
final selectedDate = await _selectDate(context);
|
||||
if (selectedDate != null) {
|
||||
setState(() {
|
||||
_selectedDate = selectedDate;
|
||||
print("Date de l'événement sélectionnée : $_selectedDate");
|
||||
});
|
||||
}
|
||||
},
|
||||
child: Text('Sélectionner la date : ${_selectedDate.toLocal()}'.split(' ')[0]),
|
||||
),
|
||||
const Icon(Icons.calendar_today, color: Colors.white70),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLocationField(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onTap: () async {
|
||||
final LatLng? pickedLocation = await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => const LocationPickerScreen(),
|
||||
),
|
||||
);
|
||||
if (pickedLocation != null) {
|
||||
setState(() {
|
||||
_selectedLatLng = pickedLocation;
|
||||
_location = '${pickedLocation.latitude}, ${pickedLocation.longitude}';
|
||||
print('Localisation sélectionnée: $_location');
|
||||
});
|
||||
} else {
|
||||
print('Localisation non sélectionnée');
|
||||
}
|
||||
},
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(10.0),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
_selectedLatLng == null
|
||||
? 'Sélectionnez une localisation'
|
||||
: 'Localisation: $_location',
|
||||
style: const TextStyle(color: Colors.white70),
|
||||
),
|
||||
const Icon(Icons.location_on, color: Colors.white70),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construction du champ de catégorie avec sélection du type et de la catégorie.
|
||||
Widget _buildCategoryField() {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
DropdownButtonFormField<String>(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Type de catégorie',
|
||||
labelStyle: const TextStyle(color: Colors.white70),
|
||||
filled: true,
|
||||
fillColor: Colors.white.withOpacity(0.1),
|
||||
border: const OutlineInputBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(10.0)),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
),
|
||||
value: _selectedCategoryType,
|
||||
items: _categories.keys.map((String type) {
|
||||
return DropdownMenuItem<String>(
|
||||
value: type,
|
||||
child: Text(type, style: const TextStyle(color: Colors.black)),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (String? newValue) {
|
||||
setState(() {
|
||||
_selectedCategoryType = newValue;
|
||||
_currentCategories = _categories[newValue] ?? [];
|
||||
_category = ''; // Réinitialiser la catégorie sélectionnée
|
||||
print('Type de catégorie sélectionné : $_selectedCategoryType');
|
||||
print('Catégories disponibles pour ce type : $_currentCategories');
|
||||
});
|
||||
actions: [
|
||||
// Bouton pour annuler l'ajout de l'événement
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
print("L'utilisateur a annulé l'ajout de l'événement.");
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
child: const Text('Annuler'),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
DropdownButtonFormField<String>(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Catégorie',
|
||||
labelStyle: const TextStyle(color: Colors.white70),
|
||||
filled: true,
|
||||
fillColor: Colors.white.withOpacity(0.1),
|
||||
border: const OutlineInputBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(10.0)),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
),
|
||||
value: _category.isNotEmpty ? _category : null,
|
||||
items: _currentCategories.map((String category) {
|
||||
return DropdownMenuItem<String>(
|
||||
value: category,
|
||||
child: Text(category, style: const TextStyle(color: Colors.black)),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (String? newValue) {
|
||||
setState(() {
|
||||
_category = newValue ?? '';
|
||||
print('Catégorie sélectionnée : $_category');
|
||||
});
|
||||
},
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
print('Erreur: Catégorie non sélectionnée');
|
||||
return 'Veuillez sélectionner une catégorie';
|
||||
// Bouton pour soumettre le formulaire et ajouter l'événement
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
if (_formKey.currentState?.validate() == true) {
|
||||
_formKey.currentState?.save();
|
||||
print("L'utilisateur a ajouté un événement : Nom = $_eventName, Date = $_selectedDate");
|
||||
Navigator.of(context).pop({
|
||||
'eventName': _eventName,
|
||||
'eventDate': _selectedDate,
|
||||
});
|
||||
}
|
||||
return null;
|
||||
},
|
||||
child: const Text('Ajouter'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildImagePicker() {
|
||||
return GestureDetector(
|
||||
onTap: () {
|
||||
// Logique pour sélectionner une image
|
||||
print('Image Picker activé');
|
||||
},
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(10.0),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
_imagePath == null
|
||||
? 'Sélectionnez une image'
|
||||
: 'Image sélectionnée: $_imagePath',
|
||||
style: const TextStyle(color: Colors.white70),
|
||||
),
|
||||
const Icon(Icons.image, color: Colors.white70),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLinkField() {
|
||||
return TextFormField(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Lien (optionnel)',
|
||||
labelStyle: const TextStyle(color: Colors.white70),
|
||||
filled: true,
|
||||
fillColor: Colors.white.withOpacity(0.1),
|
||||
border: const OutlineInputBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(10.0)),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
prefixIcon: const Icon(Icons.link, color: Colors.white70),
|
||||
),
|
||||
style: const TextStyle(color: Colors.white),
|
||||
onSaved: (value) {
|
||||
_link = value ?? '';
|
||||
print('Lien sauvegardé: $_link');
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSubmitButton() {
|
||||
return ElevatedButton(
|
||||
onPressed: () async {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
_formKey.currentState!.save();
|
||||
print('Formulaire validé');
|
||||
|
||||
EventModel newEvent = EventModel(
|
||||
id: '',
|
||||
title: _title,
|
||||
description: _description,
|
||||
date: _selectedDate?.toIso8601String() ?? '',
|
||||
location: _location,
|
||||
category: _category,
|
||||
link: _link,
|
||||
imageUrl: _imagePath ?? '',
|
||||
status: 'OPEN',
|
||||
creator: UserModel(
|
||||
userId: widget.userId,
|
||||
nom: widget.userName,
|
||||
prenoms: widget.userLastName,
|
||||
email: '',
|
||||
motDePasse: '',
|
||||
),
|
||||
participants: [
|
||||
UserModel(
|
||||
userId: widget.userId,
|
||||
nom: widget.userName,
|
||||
prenoms: widget.userLastName,
|
||||
email: '',
|
||||
motDePasse: '',
|
||||
)
|
||||
],
|
||||
);
|
||||
|
||||
Map<String, dynamic> eventData = newEvent.toJson();
|
||||
print('Données JSON de l\'événement: $eventData');
|
||||
|
||||
final response = await http.post(
|
||||
Uri.parse('${Urls.baseUrl}/events'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode(eventData),
|
||||
);
|
||||
|
||||
print('Statut de la réponse: ${response.statusCode}');
|
||||
print('Réponse brute: ${response.body}');
|
||||
|
||||
if (response.statusCode == 201) {
|
||||
print('Événement créé avec succès');
|
||||
Fluttertoast.showToast(
|
||||
msg: "Événement créé avec succès!",
|
||||
toastLength: Toast.LENGTH_SHORT,
|
||||
gravity: ToastGravity.BOTTOM,
|
||||
backgroundColor: Colors.green,
|
||||
textColor: Colors.white,
|
||||
fontSize: 16.0,
|
||||
);
|
||||
Navigator.of(context).pop(); // Fermer la boîte de dialogue
|
||||
} else {
|
||||
print('Erreur lors de la création de l\'événement: ${response.reasonPhrase}');
|
||||
Fluttertoast.showToast(
|
||||
msg: "Erreur lors de la création de l'événement",
|
||||
toastLength: Toast.LENGTH_SHORT,
|
||||
gravity: ToastGravity.BOTTOM,
|
||||
backgroundColor: Colors.red,
|
||||
textColor: Colors.white,
|
||||
fontSize: 16.0,
|
||||
);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Erreur: ${response.reasonPhrase}')),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
print('Le formulaire n\'est pas valide');
|
||||
}
|
||||
},
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: const Color(0xFF1DBF73),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(vertical: 12.0),
|
||||
minimumSize: const Size(double.infinity, 40),
|
||||
),
|
||||
child: const Text('Ajouter l\'événement', style: TextStyle(color: Colors.white)),
|
||||
/// Fonction pour afficher le sélecteur de date
|
||||
Future<DateTime?> _selectDate(BuildContext context) async {
|
||||
final DateTime? picked = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _selectedDate,
|
||||
firstDate: DateTime(2000),
|
||||
lastDate: DateTime(2101),
|
||||
);
|
||||
if (picked != null) {
|
||||
print("Date choisie dans le sélecteur : $picked");
|
||||
}
|
||||
return picked;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,35 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Écran des établissements.
|
||||
/// Cet écran affiche une liste des établissements disponibles.
|
||||
/// Les logs permettent de tracer les actions de navigation et d'affichage dans cet écran.
|
||||
class EstablishmentsScreen extends StatelessWidget {
|
||||
const EstablishmentsScreen({super.key});
|
||||
const EstablishmentsScreen({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const Center(
|
||||
child: Text(
|
||||
'Établissements',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
print("Affichage de l'écran des établissements.");
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Établissements'),
|
||||
backgroundColor: Colors.blueAccent,
|
||||
),
|
||||
body: ListView.builder(
|
||||
itemCount: 10, // Exemple : 10 établissements fictifs pour l'affichage
|
||||
itemBuilder: (context, index) {
|
||||
print("Affichage de l'établissement numéro $index.");
|
||||
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.location_city),
|
||||
title: Text('Établissement $index'),
|
||||
subtitle: const Text('Description de l\'établissement'),
|
||||
onTap: () {
|
||||
print("L'utilisateur a sélectionné l'établissement numéro $index.");
|
||||
// Logique pour ouvrir les détails de l'établissement
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,429 +1,172 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:afterwork/data/datasources/event_remote_data_source.dart';
|
||||
|
||||
import '../../../core/utils/date_formatter.dart';
|
||||
import 'package:afterwork/data/models/event_model.dart';
|
||||
import 'package:afterwork/core/utils/date_formatter.dart'; // Importer DateFormatter
|
||||
|
||||
/// Widget pour afficher une carte d'événement.
|
||||
/// Cette classe est utilisée pour afficher les détails d'un événement,
|
||||
/// incluant son titre, sa description, son image, et des actions possibles
|
||||
/// telles que réagir, commenter, partager, participer, et fermer ou rouvrir l'événement.
|
||||
class EventCard extends StatelessWidget {
|
||||
// Identifiant unique de l'événement
|
||||
final String eventId;
|
||||
// Source de données distante pour les opérations sur l'événement
|
||||
final EventRemoteDataSource eventRemoteDataSource;
|
||||
// Identifiant de l'utilisateur
|
||||
final EventModel event;
|
||||
final String userId;
|
||||
// Nom de l'utilisateur
|
||||
final String userName;
|
||||
// Prénom de l'utilisateur
|
||||
final String userLastName;
|
||||
// URL de l'image de profil de l'utilisateur
|
||||
final String profileImage;
|
||||
// Nom complet de l'utilisateur (nom + prénom)
|
||||
final String name;
|
||||
// Date de publication de l'événement
|
||||
final String datePosted;
|
||||
// Titre de l'événement
|
||||
final String eventTitle;
|
||||
// Description de l'événement
|
||||
final String eventDescription;
|
||||
// URL de l'image de l'événement
|
||||
final String eventImageUrl;
|
||||
// Statut de l'événement (e.g., "OPEN", "CLOSED")
|
||||
final String eventStatus;
|
||||
// Catégorie de l'événement
|
||||
final String eventCategory;
|
||||
// Nombre de réactions à l'événement
|
||||
final int reactionsCount;
|
||||
// Nombre de commentaires sur l'événement
|
||||
final int commentsCount;
|
||||
// Nombre de partages de l'événement
|
||||
final int sharesCount;
|
||||
// Callback pour l'action "Réagir"
|
||||
final VoidCallback onReact;
|
||||
// Callback pour l'action "Commenter"
|
||||
final VoidCallback onComment;
|
||||
// Callback pour l'action "Partager"
|
||||
final VoidCallback onShare;
|
||||
// Callback pour l'action "Participer"
|
||||
final VoidCallback onParticipate;
|
||||
// Callback pour afficher plus d'options
|
||||
final VoidCallback onMoreOptions;
|
||||
// Callback pour fermer l'événement
|
||||
final VoidCallback onCloseEvent;
|
||||
// Callback pour rouvrir l'événement
|
||||
final VoidCallback onReopenEvent;
|
||||
|
||||
const EventCard({
|
||||
Key? key,
|
||||
required this.eventId,
|
||||
required this.eventRemoteDataSource,
|
||||
required this.event,
|
||||
required this.userId,
|
||||
required this.userName,
|
||||
required this.userLastName,
|
||||
required this.profileImage,
|
||||
required this.name,
|
||||
required this.datePosted,
|
||||
required this.eventTitle,
|
||||
required this.eventDescription,
|
||||
required this.eventImageUrl,
|
||||
required this.eventStatus,
|
||||
required this.eventCategory,
|
||||
required this.reactionsCount,
|
||||
required this.commentsCount,
|
||||
required this.sharesCount,
|
||||
required this.onReact,
|
||||
required this.onComment,
|
||||
required this.onShare,
|
||||
required this.onParticipate,
|
||||
required this.onMoreOptions,
|
||||
required this.onCloseEvent,
|
||||
required this.onReopenEvent,
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Log du rendu de la carte d'événement
|
||||
print('Rendu de l\'EventCard pour l\'événement $eventId avec statut $eventStatus');
|
||||
|
||||
return AnimatedOpacity(
|
||||
opacity: 1.0,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
child: Dismissible(
|
||||
key: ValueKey(eventId),
|
||||
direction: eventStatus == 'CLOSED'
|
||||
? DismissDirection.endToStart // Permet de rouvrir avec un swipe à gauche
|
||||
: DismissDirection.startToEnd, // Permet de fermer avec un swipe à droite
|
||||
onDismissed: (direction) {
|
||||
if (direction == DismissDirection.startToEnd) {
|
||||
// Log du déclenchement de la fermeture de l'événement
|
||||
print('Tentative de fermeture de l\'événement $eventId');
|
||||
onCloseEvent();
|
||||
} else if (direction == DismissDirection.endToStart && eventStatus == 'CLOSED') {
|
||||
// Log du déclenchement de la réouverture de l'événement
|
||||
print('Tentative de réouverture de l\'événement $eventId');
|
||||
onReopenEvent();
|
||||
}
|
||||
},
|
||||
background: Container(
|
||||
color: Colors.red,
|
||||
alignment: Alignment.centerLeft,
|
||||
padding: const EdgeInsets.only(left: 20.0),
|
||||
child: const Icon(Icons.delete, color: Colors.white),
|
||||
),
|
||||
secondaryBackground: Container(
|
||||
color: Colors.green,
|
||||
alignment: Alignment.centerRight,
|
||||
padding: const EdgeInsets.only(right: 20.0),
|
||||
child: const Icon(Icons.replay, color: Colors.white),
|
||||
),
|
||||
child: Stack(
|
||||
return Card(
|
||||
color: const Color(0xFF2C2C3E),
|
||||
margin: const EdgeInsets.symmetric(vertical: 10.0),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15.0)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Card(
|
||||
color: const Color(0xFF2C2C3E),
|
||||
margin: const EdgeInsets.symmetric(vertical: 10.0),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(15.0),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildHeader(context),
|
||||
const SizedBox(height: 10),
|
||||
_buildEventCategory(),
|
||||
const SizedBox(height: 5),
|
||||
_buildEventDetails(),
|
||||
const SizedBox(height: 10),
|
||||
_buildEventImage(),
|
||||
const SizedBox(height: 10),
|
||||
Divider(color: Colors.white.withOpacity(0.2)),
|
||||
_buildInteractionRow(),
|
||||
const SizedBox(height: 5),
|
||||
_buildParticipateButton(),
|
||||
],
|
||||
),
|
||||
),
|
||||
_buildHeader(),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
event.title,
|
||||
style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 5),
|
||||
Text(
|
||||
event.description,
|
||||
style: const TextStyle(color: Colors.white70, fontSize: 14),
|
||||
maxLines: 3,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_buildEventImage(),
|
||||
const Divider(color: Colors.white24),
|
||||
_buildInteractionRow(),
|
||||
const SizedBox(height: 10),
|
||||
_buildStatusAndActions(),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construire l'en-tête de la carte avec les informations de l'utilisateur.
|
||||
/// Cette méthode affiche l'image de profil, le nom de l'utilisateur, la date
|
||||
/// de publication de l'événement, et le statut de l'événement.
|
||||
Widget _buildHeader(BuildContext context) {
|
||||
// Log du rendu de l'en-tête de la carte
|
||||
print('Rendu de l\'en-tête pour l\'événement $eventId');
|
||||
// Convertir la date `datePosted` en DateTime si ce n'est pas déjà fait
|
||||
DateTime dateTimePosted = DateTime.parse(datePosted);
|
||||
Widget _buildHeader() {
|
||||
// Convertir la date de l'événement (de String à DateTime)
|
||||
DateTime? eventDate;
|
||||
try {
|
||||
eventDate = DateTime.parse(event.startDate);
|
||||
} catch (e) {
|
||||
eventDate = null; // Gérer le cas où la date ne serait pas valide
|
||||
}
|
||||
|
||||
// Utiliser le DateFormatter pour formater la date
|
||||
String formattedDate = DateFormatter.formatDate(dateTimePosted);
|
||||
// Utiliser DateFormatter pour afficher une date lisible si elle est valide
|
||||
String formattedDate = eventDate != null ? DateFormatter.formatDate(eventDate) : 'Date inconnue';
|
||||
|
||||
return Row(
|
||||
children: [
|
||||
CircleAvatar(
|
||||
backgroundImage: AssetImage(profileImage),
|
||||
radius: 25,
|
||||
),
|
||||
CircleAvatar(backgroundImage: NetworkImage(event.imageUrl ?? 'lib/assets/images/placeholder.png')),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
name,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
formattedDate,
|
||||
style: const TextStyle(color: Colors.white70, fontSize: 14),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
_buildStatusBadge(), // Badge de statut aligné sur la même ligne que la date du post
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'$userName $userLastName',
|
||||
style: const TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 5),
|
||||
Text(
|
||||
formattedDate, // Utiliser la date formatée ici
|
||||
style: const TextStyle(color: Colors.white70, fontSize: 14),
|
||||
),
|
||||
],
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.more_vert, color: Colors.white),
|
||||
onPressed: () {
|
||||
// Log du déclenchement du bouton "Plus d'options"
|
||||
print('Plus d\'options déclenché pour l\'événement $eventId');
|
||||
onMoreOptions();
|
||||
// Logique d'affichage d'options supplémentaires pour l'événement.
|
||||
// Vous pouvez utiliser un menu déroulant ou une boîte de dialogue ici.
|
||||
},
|
||||
),
|
||||
if (eventStatus != 'CLOSED') // Masquer le bouton de fermeture si l'événement est fermé
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close, color: Colors.white),
|
||||
onPressed: () {
|
||||
// Log du déclenchement du bouton de fermeture de l'événement
|
||||
print('Tentative de fermeture de l\'événement $eventId');
|
||||
onCloseEvent();
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Afficher la catégorie de l'événement au-dessus du titre.
|
||||
/// Cette méthode affiche la catégorie en italique pour distinguer le type d'événement.
|
||||
Widget _buildEventCategory() {
|
||||
// Log du rendu de la catégorie de l'événement
|
||||
print('Affichage de la catégorie pour l\'événement $eventId: $eventCategory');
|
||||
|
||||
return Text(
|
||||
eventCategory,
|
||||
style: const TextStyle(
|
||||
color: Colors.blueAccent,
|
||||
fontSize: 14,
|
||||
fontStyle: FontStyle.italic, // Style en italique
|
||||
fontWeight: FontWeight.w400, // Titre fin
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Afficher les détails de l'événement.
|
||||
/// Cette méthode affiche le titre et la description de l'événement.
|
||||
Widget _buildEventDetails() {
|
||||
// Log du rendu des détails de l'événement
|
||||
print('Affichage des détails pour l\'événement $eventId');
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
eventTitle,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 5),
|
||||
Text(
|
||||
eventDescription,
|
||||
style: const TextStyle(color: Colors.white70, fontSize: 14),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Afficher l'image de l'événement.
|
||||
/// Cette méthode affiche l'image associée à l'événement.
|
||||
Widget _buildEventImage() {
|
||||
// Log du rendu de l'image de l'événement
|
||||
print('Affichage de l\'image pour l\'événement $eventId');
|
||||
|
||||
return ClipRRect(
|
||||
borderRadius: BorderRadius.circular(10.0),
|
||||
child: Image.network(
|
||||
eventImageUrl,
|
||||
height: 180,
|
||||
width: double.infinity,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (context, error, stackTrace) {
|
||||
// Log de l'erreur lors du chargement de l'image
|
||||
print('Erreur de chargement de l\'image pour l\'événement $eventId: $error');
|
||||
return Image.asset(
|
||||
'lib/assets/images/placeholder.png',
|
||||
height: 180,
|
||||
width: double.infinity,
|
||||
fit: BoxFit.cover,
|
||||
);
|
||||
},
|
||||
event.imageUrl ?? 'lib/assets/images/placeholder.png',
|
||||
height: 180,
|
||||
width: double.infinity,
|
||||
fit: BoxFit.cover,
|
||||
errorBuilder: (context, error, stackTrace) {
|
||||
return Image.asset('lib/assets/images/placeholder.png'); // Image par défaut si erreur de chargement
|
||||
}
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Afficher les icônes d'interaction (réagir, commenter, partager).
|
||||
/// Cette méthode affiche les boutons pour réagir, commenter, et partager l'événement.
|
||||
Widget _buildInteractionRow() {
|
||||
// Log du rendu de la ligne d'interaction de l'événement
|
||||
print('Affichage des interactions pour l\'événement $eventId');
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4.0), // Réduire le padding vertical
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround, // Utiliser spaceAround pour réduire l'espace
|
||||
children: [
|
||||
Expanded(
|
||||
child: _buildIconButton(
|
||||
icon: Icons.thumb_up_alt_outlined,
|
||||
label: 'Réagir',
|
||||
count: reactionsCount,
|
||||
onPressed: () {
|
||||
// Log de l'action "Réagir"
|
||||
print('Réaction à l\'événement $eventId');
|
||||
onReact();
|
||||
},
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: _buildIconButton(
|
||||
icon: Icons.comment_outlined,
|
||||
label: 'Commenter',
|
||||
count: commentsCount,
|
||||
onPressed: () {
|
||||
// Log de l'action "Commenter"
|
||||
print('Commentaire sur l\'événement $eventId');
|
||||
onComment();
|
||||
},
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: _buildIconButton(
|
||||
icon: Icons.share_outlined,
|
||||
label: 'Partager',
|
||||
count: sharesCount,
|
||||
onPressed: () {
|
||||
// Log de l'action "Partager"
|
||||
print('Partage de l\'événement $eventId');
|
||||
onShare();
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
_buildIconButton(Icons.thumb_up_alt_outlined, 'Réagir', event.reactionsCount, onReact),
|
||||
_buildIconButton(Icons.comment_outlined, 'Commenter', event.commentsCount, onComment),
|
||||
_buildIconButton(Icons.share_outlined, 'Partager', event.sharesCount, onShare),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Bouton d'interaction personnalisé.
|
||||
/// Cette méthode construit un bouton avec une icône et un label pour l'interaction.
|
||||
Widget _buildIconButton({
|
||||
required IconData icon,
|
||||
required String label,
|
||||
required int count,
|
||||
required VoidCallback onPressed,
|
||||
}) {
|
||||
// Log de la construction du bouton d'interaction
|
||||
print('Construction du bouton $label pour l\'événement $eventId');
|
||||
|
||||
Widget _buildIconButton(IconData icon, String label, int count, VoidCallback onPressed) {
|
||||
return TextButton.icon(
|
||||
onPressed: onPressed,
|
||||
icon: Icon(icon, color: const Color(0xFF1DBF73), size: 20),
|
||||
label: Text(
|
||||
'$label ($count)',
|
||||
style: const TextStyle(color: Colors.white70, fontSize: 12),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Bouton pour participer à l'événement.
|
||||
/// Cette méthode construit un bouton qui permet de participer à l'événement.
|
||||
/// Si l'événement est fermé, le bouton est caché.
|
||||
Widget _buildParticipateButton() {
|
||||
// Log de la construction du bouton "Participer"
|
||||
print('Construction du bouton "Participer" pour l\'événement $eventId avec statut $eventStatus');
|
||||
|
||||
// Si l'événement est fermé, ne rien retourner (pas de bouton)
|
||||
if (eventStatus == 'CLOSED') {
|
||||
print('L\'événement $eventId est fermé, le bouton "Participer" est caché.');
|
||||
return SizedBox.shrink(); // Retourne un widget vide pour ne pas occuper d'espace
|
||||
}
|
||||
|
||||
// Sinon, retourner le bouton "Participer"
|
||||
return ElevatedButton(
|
||||
onPressed: onParticipate,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: const Color(0xFF1DBF73),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
// Widget pour afficher le statut de l'événement et les actions associées (fermer, réouvrir)
|
||||
Widget _buildStatusAndActions() {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
event.status == 'closed' ? 'Événement fermé' : 'Événement ouvert',
|
||||
style: TextStyle(
|
||||
color: event.status == 'closed' ? Colors.red : Colors.green,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(vertical: 12.0),
|
||||
minimumSize: const Size(double.infinity, 40),
|
||||
),
|
||||
child: const Text(
|
||||
'Participer',
|
||||
style: TextStyle(color: Colors.white),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construire un badge pour afficher le statut de l'événement.
|
||||
/// Cette méthode affiche un badge avec le statut de l'événement ("OPEN" ou "CLOSED").
|
||||
Widget _buildStatusBadge() {
|
||||
// Log de la construction du badge de statut
|
||||
print('Construction du badge de statut pour l\'événement $eventId: $eventStatus');
|
||||
|
||||
Color badgeColor;
|
||||
switch (eventStatus) {
|
||||
case 'CLOSED':
|
||||
badgeColor = Colors.redAccent;
|
||||
break;
|
||||
case 'OPEN':
|
||||
default:
|
||||
badgeColor = Colors.greenAccent;
|
||||
break;
|
||||
}
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
|
||||
decoration: BoxDecoration(
|
||||
color: badgeColor.withOpacity(0.7),
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
),
|
||||
child: Text(
|
||||
eventStatus.toUpperCase(),
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 10, // Réduction de la taille du texte
|
||||
fontWeight: FontWeight.bold,
|
||||
event.status == 'closed'
|
||||
? ElevatedButton(
|
||||
onPressed: onReopenEvent,
|
||||
child: const Text('Rouvrir l\'événement'),
|
||||
)
|
||||
: ElevatedButton(
|
||||
onPressed: onCloseEvent,
|
||||
child: const Text('Fermer l\'événement'),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:afterwork/data/models/event_model.dart';
|
||||
import 'package:afterwork/data/datasources/event_remote_data_source.dart';
|
||||
import 'event_card.dart';
|
||||
import 'package:afterwork/presentation/screens/event/event_card.dart';
|
||||
import '../../state_management/event_bloc.dart';
|
||||
import '../dialogs/add_event_dialog.dart';
|
||||
|
||||
/// Écran principal pour afficher les événements.
|
||||
class EventScreen extends StatefulWidget {
|
||||
final EventRemoteDataSource eventRemoteDataSource;
|
||||
final String userId;
|
||||
final String userName; // Nom de l'utilisateur
|
||||
final String userLastName; // Prénom de l'utilisateur
|
||||
final String userName;
|
||||
final String userLastName;
|
||||
|
||||
const EventScreen({
|
||||
Key? key,
|
||||
required this.eventRemoteDataSource,
|
||||
required this.userId,
|
||||
required this.userName,
|
||||
required this.userLastName,
|
||||
@@ -24,13 +22,11 @@ class EventScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _EventScreenState extends State<EventScreen> {
|
||||
late Future<List<EventModel>> _eventsFuture;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Récupérer la liste des événements à partir de la source de données distante
|
||||
_eventsFuture = widget.eventRemoteDataSource.getAllEvents();
|
||||
// Charger les événements lors de l'initialisation
|
||||
context.read<EventBloc>().add(LoadEvents(widget.userId));
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -60,161 +56,98 @@ class _EventScreenState extends State<EventScreen> {
|
||||
);
|
||||
|
||||
if (eventData != null) {
|
||||
try {
|
||||
print('Tentative de création d\'un nouvel événement par l\'utilisateur ${widget.userId}');
|
||||
await widget.eventRemoteDataSource.createEvent(eventData as EventModel);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Événement ajouté avec succès !')),
|
||||
);
|
||||
// Réactualiser la liste des événements après création
|
||||
setState(() {
|
||||
_eventsFuture = widget.eventRemoteDataSource.getAllEvents();
|
||||
});
|
||||
} catch (e) {
|
||||
print('Erreur lors de la création de l\'événement: $e');
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Erreur : $e')),
|
||||
);
|
||||
}
|
||||
// Ajouter l'événement en appelant l'API via le bloc
|
||||
context.read<EventBloc>().add(AddEvent(EventModel.fromJson(eventData)));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Événement ajouté avec succès !')),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
body: FutureBuilder<List<EventModel>>(
|
||||
future: _eventsFuture,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
||||
body: BlocBuilder<EventBloc, EventState>(
|
||||
builder: (context, state) {
|
||||
if (state is EventLoading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
} else if (snapshot.hasError) {
|
||||
print('Erreur lors de la récupération des événements: ${snapshot.error}');
|
||||
return Center(child: Text('Erreur: ${snapshot.error}'));
|
||||
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
|
||||
return const Center(child: Text('Aucun événement trouvé.'));
|
||||
} else if (state is EventLoaded) {
|
||||
final events = state.events;
|
||||
if (events.isEmpty) {
|
||||
return const Center(child: Text('Aucun événement disponible.'));
|
||||
}
|
||||
return ListView.builder(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
itemCount: events.length,
|
||||
itemBuilder: (context, index) {
|
||||
final event = events[index];
|
||||
return EventCard(
|
||||
key: ValueKey(event.id),
|
||||
event: event,
|
||||
userId: widget.userId,
|
||||
userName: widget.userName,
|
||||
userLastName: widget.userLastName,
|
||||
onReact: () => _onReact(event.id),
|
||||
onComment: () => _onComment(event.id),
|
||||
onShare: () => _onShare(event.id),
|
||||
onParticipate: () => _onParticipate(event.id),
|
||||
onCloseEvent: () => _onCloseEvent(event.id),
|
||||
onReopenEvent: () => _onReopenEvent(event.id),
|
||||
);
|
||||
},
|
||||
);
|
||||
} else if (state is EventError) {
|
||||
return Center(child: Text('Erreur: ${state.message}'));
|
||||
}
|
||||
|
||||
final events = snapshot.data!;
|
||||
print('Nombre d\'événements récupérés: ${events.length}');
|
||||
|
||||
return ListView.builder(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
itemCount: events.length,
|
||||
itemBuilder: (context, index) {
|
||||
final event = events[index];
|
||||
print('Affichage de l\'événement ${event.id}');
|
||||
|
||||
return EventCard(
|
||||
key: ValueKey(event.id),
|
||||
eventRemoteDataSource: widget.eventRemoteDataSource,
|
||||
userId: widget.userId,
|
||||
eventId: event.id,
|
||||
userName: widget.userName,
|
||||
userLastName: widget.userLastName,
|
||||
profileImage: 'lib/assets/images/profile_picture.png',
|
||||
name: '${widget.userName} ${widget.userLastName}',
|
||||
eventCategory: event.category,
|
||||
datePosted: event.date,
|
||||
eventTitle: event.title,
|
||||
eventDescription: event.description,
|
||||
eventImageUrl: event.imageUrl ?? 'lib/assets/images/placeholder.png',
|
||||
eventStatus: event.status,
|
||||
reactionsCount: 120, // Exemple de valeur
|
||||
commentsCount: 45, // Exemple de valeur
|
||||
sharesCount: 30, // Exemple de valeur
|
||||
onReact: () {
|
||||
print('Réaction à l\'événement ${event.id}');
|
||||
},
|
||||
onComment: () {
|
||||
print('Commentaire sur l\'événement ${event.id}');
|
||||
},
|
||||
onShare: () {
|
||||
print('Partage de l\'événement ${event.id}');
|
||||
},
|
||||
onParticipate: () {
|
||||
print('Participation à l\'événement ${event.id}');
|
||||
},
|
||||
onCloseEvent: () => _onCloseEvent(context, event.id, index),
|
||||
onMoreOptions: () {
|
||||
print('Affichage des options pour l\'événement ${event.id}');
|
||||
},
|
||||
onReopenEvent: () => _onReopenEvent(context, event.id, index),
|
||||
);
|
||||
},
|
||||
);
|
||||
return const Center(child: Text('Aucun événement disponible.'));
|
||||
},
|
||||
),
|
||||
backgroundColor: const Color(0xFF1E1E2C),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
onPressed: () {
|
||||
// Recharger les événements
|
||||
context.read<EventBloc>().add(LoadEvents(widget.userId));
|
||||
},
|
||||
backgroundColor: const Color(0xFF1DBF73),
|
||||
child: const Icon(Icons.refresh),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Logique pour fermer un événement
|
||||
void _onCloseEvent(BuildContext context, String eventId, int index) async {
|
||||
try {
|
||||
print('Tentative de fermeture de l\'événement $eventId');
|
||||
|
||||
// Appeler l'API pour fermer l'événement
|
||||
await widget.eventRemoteDataSource.closeEvent(eventId);
|
||||
print('Événement fermé avec succès');
|
||||
|
||||
// Montrer un message de succès AVANT de supprimer l'événement de la liste
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('L\'événement a été fermé avec succès.')),
|
||||
);
|
||||
|
||||
// Supprimez l'événement de la liste après avoir affiché le SnackBar
|
||||
setState(() {
|
||||
_eventsFuture = _eventsFuture.then((events) {
|
||||
events.removeAt(index);
|
||||
return events;
|
||||
});
|
||||
});
|
||||
} catch (e) {
|
||||
print('Erreur lors de la fermeture de l\'événement: $e');
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Erreur lors de la fermeture de l\'événement : $e')),
|
||||
);
|
||||
}
|
||||
void _onReact(String eventId) {
|
||||
print('Réaction à l\'événement $eventId');
|
||||
// Implémentez la logique pour réagir à un événement ici
|
||||
}
|
||||
|
||||
/// Logique pour rouvrir un événement
|
||||
void _onReopenEvent(BuildContext context, String eventId, int index) async {
|
||||
try {
|
||||
print('Tentative de réouverture de l\'événement $eventId');
|
||||
await widget.eventRemoteDataSource.reopenEvent(eventId);
|
||||
print('Événement rouvert avec succès');
|
||||
void _onComment(String eventId) {
|
||||
print('Commentaire sur l\'événement $eventId');
|
||||
// Implémentez la logique pour commenter un événement ici
|
||||
}
|
||||
|
||||
// Montrer un message de succès
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('L\'événement a été rouvert avec succès.')),
|
||||
);
|
||||
void _onShare(String eventId) {
|
||||
print('Partage de l\'événement $eventId');
|
||||
// Implémentez la logique pour partager un événement ici
|
||||
}
|
||||
|
||||
// Mettre à jour le statut de l'événement dans la liste des événements
|
||||
setState(() {
|
||||
_eventsFuture = _eventsFuture.then((events) {
|
||||
final updatedEvent = EventModel(
|
||||
id: events[index].id,
|
||||
title: events[index].title,
|
||||
description: events[index].description,
|
||||
date: events[index].date,
|
||||
location: events[index].location,
|
||||
category: events[index].category,
|
||||
link: events[index].link,
|
||||
imageUrl: events[index].imageUrl,
|
||||
creator: events[index].creator,
|
||||
participants: events[index].participants,
|
||||
status: 'OPEN', // Mettre à jour le statut à 'OPEN'
|
||||
);
|
||||
void _onParticipate(String eventId) {
|
||||
print('Participation à l\'événement $eventId');
|
||||
// Implémentez la logique pour participer à un événement ici
|
||||
}
|
||||
|
||||
// Remplacer l'événement dans la liste
|
||||
events[index] = updatedEvent;
|
||||
return events;
|
||||
});
|
||||
});
|
||||
} catch (e) {
|
||||
print('Erreur lors de la réouverture de l\'événement: $e');
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Erreur lors de la réouverture de l\'événement : $e')),
|
||||
);
|
||||
}
|
||||
void _onCloseEvent(String eventId) {
|
||||
print('Fermeture de l\'événement $eventId');
|
||||
// Appeler le bloc pour fermer l'événement
|
||||
context.read<EventBloc>().add(CloseEvent(eventId));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('L\'événement a été fermé avec succès.')),
|
||||
);
|
||||
}
|
||||
|
||||
void _onReopenEvent(String eventId) {
|
||||
print('Réouverture de l\'événement $eventId');
|
||||
// Appeler le bloc pour rouvrir l'événement
|
||||
context.read<EventBloc>().add(ReopenEvent(eventId));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('L\'événement a été rouvert avec succès.')),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,163 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../core/constants/colors.dart'; // Importez les couleurs dynamiques
|
||||
import '../../widgets/friend_suggestions.dart';
|
||||
import '../../widgets/group_list.dart';
|
||||
import '../../widgets/popular_activity_list.dart';
|
||||
import '../../widgets/quick_action_button.dart';
|
||||
import '../../widgets/recommended_event_list.dart';
|
||||
import '../../widgets/section_header.dart';
|
||||
import '../../widgets/story_section.dart';
|
||||
|
||||
class HomeContentScreen extends StatelessWidget {
|
||||
const HomeContentScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const Center(
|
||||
child: Text(
|
||||
'Accueil',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
final size = MediaQuery.of(context).size;
|
||||
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 15.0), // Marges réduites
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Section de bienvenue
|
||||
_buildWelcomeCard(),
|
||||
|
||||
const SizedBox(height: 15), // Espacement vertical réduit
|
||||
|
||||
// Section "Moments populaires"
|
||||
_buildCard(
|
||||
context: context,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SectionHeader(
|
||||
title: 'Moments populaires',
|
||||
icon: Icons.camera_alt,
|
||||
textStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.w500), // Taille ajustée
|
||||
),
|
||||
const SizedBox(height: 10), // Espace vertical réduit
|
||||
StorySection(size: size),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 15), // Espacement réduit
|
||||
|
||||
// Section des événements recommandés
|
||||
_buildCard(
|
||||
context: context,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SectionHeader(
|
||||
title: 'Événements recommandés',
|
||||
icon: Icons.star,
|
||||
textStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
|
||||
),
|
||||
const SizedBox(height: 10), // Espacement réduit
|
||||
RecommendedEventList(size: size),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 15), // Espacement réduit
|
||||
|
||||
// Section des activités populaires
|
||||
_buildCard(
|
||||
context: context,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SectionHeader(
|
||||
title: 'Activités populaires',
|
||||
icon: Icons.local_activity,
|
||||
textStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
|
||||
),
|
||||
const SizedBox(height: 10), // Espacement réduit
|
||||
PopularActivityList(size: size),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 15), // Espacement réduit
|
||||
|
||||
// Section des groupes sociaux
|
||||
_buildCard(
|
||||
context: context,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SectionHeader(
|
||||
title: 'Groupes à rejoindre',
|
||||
icon: Icons.group_add,
|
||||
textStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
|
||||
),
|
||||
const SizedBox(height: 10), // Espacement réduit
|
||||
GroupList(size: size),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 15), // Espacement réduit
|
||||
|
||||
// Section des suggestions d'amis
|
||||
_buildCard(
|
||||
context: context,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const SectionHeader(
|
||||
title: 'Suggestions d’amis',
|
||||
icon: Icons.person_add,
|
||||
textStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
|
||||
),
|
||||
const SizedBox(height: 10), // Espacement réduit
|
||||
FriendSuggestions(size: size),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Widget pour la carte de bienvenue
|
||||
Widget _buildWelcomeCard() {
|
||||
return Card(
|
||||
elevation: 5,
|
||||
color: AppColors.surface, // Utilisation de la couleur dynamique pour la surface
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
'Bienvenue, Dahoud!',
|
||||
style: TextStyle(
|
||||
color: AppColors.textPrimary, // Texte dynamique
|
||||
fontSize: 22, // Taille de police réduite
|
||||
fontWeight: FontWeight.w600, // Poids de police ajusté
|
||||
),
|
||||
),
|
||||
Icon(Icons.waving_hand, color: Colors.orange.shade300, size: 24), // Taille de l'icône ajustée
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Widget générique pour créer une carte design avec des espaces optimisés
|
||||
Widget _buildCard({required BuildContext context, required Widget child}) {
|
||||
return Card(
|
||||
elevation: 3, // Réduction de l'élévation pour un look plus épuré
|
||||
color: AppColors.surface, // Utilisation de la couleur dynamique pour la surface
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), // Coins légèrement arrondis
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12.0), // Padding interne réduit pour un contenu plus compact
|
||||
child: child,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart'; // Pour ThemeProvider
|
||||
import 'package:afterwork/presentation/screens/event/event_screen.dart';
|
||||
import 'package:afterwork/presentation/screens/profile/profile_screen.dart';
|
||||
import 'package:afterwork/presentation/screens/social/social_screen.dart';
|
||||
import 'package:afterwork/presentation/screens/establishments/establishments_screen.dart';
|
||||
import 'package:afterwork/presentation/screens/home/home_content.dart';
|
||||
import 'package:afterwork/data/datasources/event_remote_data_source.dart';
|
||||
import 'package:afterwork/presentation/screens/notifications/notifications_screen.dart'; // Importez l'écran de notifications
|
||||
|
||||
import '../../../core/constants/colors.dart';
|
||||
import '../../../core/theme/theme_provider.dart'; // Pour basculer le thème
|
||||
|
||||
/// Classe principale pour l'écran d'accueil de l'application.
|
||||
/// Cette classe gère la navigation entre les différentes sections de l'application
|
||||
/// en utilisant un [TabController] pour contrôler les différents onglets.
|
||||
/// Les actions de l'AppBar sont également personnalisées pour offrir des fonctionnalités
|
||||
/// spécifiques comme la recherche, la publication et la messagerie.
|
||||
class HomeScreen extends StatefulWidget {
|
||||
final EventRemoteDataSource eventRemoteDataSource;
|
||||
final String userId;
|
||||
final String userName;
|
||||
final String userLastName;
|
||||
final String userProfileImage; // Ajouter un champ pour l'image de profil de l'utilisateur
|
||||
|
||||
const HomeScreen({
|
||||
Key? key,
|
||||
@@ -23,6 +24,7 @@ class HomeScreen extends StatefulWidget {
|
||||
required this.userId,
|
||||
required this.userName,
|
||||
required this.userLastName,
|
||||
required this.userProfileImage, // Passer l'image de profil ici
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
@@ -35,136 +37,207 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Initialisation du TabController avec 5 onglets.
|
||||
_tabController = TabController(length: 5, vsync: this);
|
||||
debugPrint('HomeScreen initialisé avec userId: ${widget.userId}, userName: ${widget.userName}, userLastName: ${widget.userLastName}');
|
||||
_tabController = TabController(length: 6, vsync: this); // Ajouter un onglet pour les notifications
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
// Nettoyage du TabController pour éviter les fuites de mémoire.
|
||||
_tabController.dispose();
|
||||
super.dispose();
|
||||
debugPrint('HomeScreen dispose appelé');
|
||||
}
|
||||
|
||||
/// Gestion des sélections dans le menu contextuel de l'AppBar.
|
||||
void _onMenuSelected(BuildContext context, String option) {
|
||||
switch (option) {
|
||||
case 'Publier':
|
||||
debugPrint('Option "Publier" sélectionnée');
|
||||
// Rediriger vers la page de publication.
|
||||
print('Publier sélectionné');
|
||||
break;
|
||||
case 'Story':
|
||||
debugPrint('Option "Story" sélectionnée');
|
||||
// Rediriger vers la page de création de Story.
|
||||
print('Story sélectionné');
|
||||
break;
|
||||
default:
|
||||
debugPrint('Option inconnue sélectionnée: $option');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Accès au ThemeProvider
|
||||
final themeProvider = Provider.of<ThemeProvider>(context);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.black,
|
||||
elevation: 0,
|
||||
leading: Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Image.asset(
|
||||
'lib/assets/images/logo.png', // Chemin correct de votre logo.
|
||||
height: 40,
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
// Bouton pour ajouter du contenu (Publier, Story).
|
||||
CircleAvatar(
|
||||
backgroundColor: Colors.white,
|
||||
radius: 18,
|
||||
child: PopupMenuButton<String>(
|
||||
onSelected: (value) {
|
||||
_onMenuSelected(context, value);
|
||||
debugPrint('Menu contextuel sélectionné: $value');
|
||||
},
|
||||
itemBuilder: (context) => [
|
||||
const PopupMenuItem(
|
||||
value: 'Publier',
|
||||
child: Text('Publier'),
|
||||
body: NestedScrollView(
|
||||
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
|
||||
return <Widget>[
|
||||
SliverAppBar(
|
||||
backgroundColor: AppColors.backgroundColor, // Gère dynamiquement la couleur d'arrière-plan
|
||||
floating: true,
|
||||
pinned: true,
|
||||
snap: true,
|
||||
elevation: 2, // Réduction de l'élévation pour un design plus léger
|
||||
leading: Padding(
|
||||
padding: const EdgeInsets.all(4.0), // Réduction du padding
|
||||
child: Image.asset(
|
||||
'lib/assets/images/logo.png',
|
||||
height: 40, // Taille réduite du logo
|
||||
),
|
||||
const PopupMenuItem(
|
||||
value: 'Story',
|
||||
child: Text('Story'),
|
||||
),
|
||||
actions: [
|
||||
_buildActionIcon(Icons.add, 'Publier', context),
|
||||
_buildActionIcon(Icons.search, 'Rechercher', context),
|
||||
_buildActionIcon(Icons.message, 'Message', context),
|
||||
_buildNotificationsIcon(context, 45),
|
||||
|
||||
// Ajout du bouton pour basculer entre les thèmes
|
||||
Switch(
|
||||
value: themeProvider.isDarkMode,
|
||||
onChanged: (value) {
|
||||
themeProvider.toggleTheme(); // Bascule le thème lorsqu'on clique
|
||||
},
|
||||
activeColor: AppColors.accentColor,
|
||||
),
|
||||
],
|
||||
icon: const Icon(Icons.add, color: Colors.blueAccent, size: 20),
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8), // Espacement entre les boutons.
|
||||
bottom: TabBar(
|
||||
controller: _tabController,
|
||||
indicatorColor: AppColors.lightPrimary, // Tab active en bleu
|
||||
labelStyle: const TextStyle(
|
||||
fontSize: 12, // Réduction de la taille du texte des onglets
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
unselectedLabelStyle: const TextStyle(
|
||||
fontSize: 11, // Réduction pour les onglets non sélectionnés
|
||||
),
|
||||
// Changement des couleurs pour les tabs non sélectionnées et sélectionnées
|
||||
labelColor: AppColors.lightPrimary, // Tab active en bleu
|
||||
unselectedLabelColor: AppColors.iconSecondary, // Tabs non sélectionnées en blanc
|
||||
|
||||
// Bouton Recherche.
|
||||
CircleAvatar(
|
||||
backgroundColor: Colors.white,
|
||||
radius: 18,
|
||||
child: IconButton(
|
||||
icon: const Icon(Icons.search, color: Colors.blueAccent, size: 20),
|
||||
onPressed: () {
|
||||
debugPrint('Bouton Recherche appuyé');
|
||||
// Implémenter la logique de recherche ici.
|
||||
},
|
||||
tabs: [
|
||||
const Tab(icon: Icon(Icons.home, size: 24), text: 'Accueil'),
|
||||
const Tab(icon: Icon(Icons.event, size: 24), text: 'Événements'),
|
||||
const Tab(icon: Icon(Icons.location_city, size: 24), text: 'Établissements'),
|
||||
const Tab(icon: Icon(Icons.people, size: 24), text: 'Social'),
|
||||
const Tab(icon: Icon(Icons.notifications, size: 24), text: 'Notifications'),
|
||||
_buildProfileTab(),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8), // Espacement entre les boutons.
|
||||
|
||||
// Bouton Messagerie.
|
||||
CircleAvatar(
|
||||
backgroundColor: Colors.white,
|
||||
radius: 18,
|
||||
child: IconButton(
|
||||
icon: const Icon(Icons.message, color: Colors.blueAccent, size: 20),
|
||||
onPressed: () {
|
||||
debugPrint('Bouton Messagerie appuyé');
|
||||
// Implémenter la logique de messagerie ici.
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8), // Espacement entre les boutons.
|
||||
],
|
||||
bottom: TabBar(
|
||||
];
|
||||
},
|
||||
body: TabBarView(
|
||||
controller: _tabController,
|
||||
indicatorColor: Colors.blueAccent,
|
||||
labelColor: Colors.white, // Couleur du texte sélectionné.
|
||||
unselectedLabelColor: Colors.grey[400], // Couleur du texte non sélectionné.
|
||||
onTap: (index) {
|
||||
debugPrint('Onglet sélectionné: $index');
|
||||
},
|
||||
tabs: const [
|
||||
Tab(icon: Icon(Icons.home), text: 'Accueil'),
|
||||
Tab(icon: Icon(Icons.event), text: 'Événements'),
|
||||
Tab(icon: Icon(Icons.location_city), text: 'Établissements'),
|
||||
Tab(icon: Icon(Icons.people), text: 'Social'),
|
||||
Tab(icon: Icon(Icons.person), text: 'Profil'),
|
||||
children: [
|
||||
const HomeContentScreen(),
|
||||
EventScreen(
|
||||
userId: widget.userId,
|
||||
userName: widget.userName,
|
||||
userLastName: widget.userLastName,
|
||||
),
|
||||
const EstablishmentsScreen(),
|
||||
const SocialScreen(),
|
||||
const NotificationsScreen(),
|
||||
const ProfileScreen(),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: TabBarView(
|
||||
controller: _tabController,
|
||||
);
|
||||
}
|
||||
|
||||
// Widget pour afficher la photo de profil de l'utilisateur dans l'onglet
|
||||
Tab _buildProfileTab() {
|
||||
return Tab(
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(
|
||||
color: Colors.blue, // Définir la couleur de la bordure ici
|
||||
width: 2.0,
|
||||
),
|
||||
),
|
||||
child: CircleAvatar(
|
||||
radius: 16, // Ajustez la taille si nécessaire
|
||||
backgroundColor: Colors.grey[200], // Couleur de fond pour le cas où l'image ne charge pas
|
||||
child: ClipOval(
|
||||
child: FadeInImage.assetNetwork(
|
||||
placeholder: 'lib/assets/images/user_placeholder.png', // Chemin de l'image par défaut
|
||||
image: widget.userProfileImage,
|
||||
fit: BoxFit.cover,
|
||||
imageErrorBuilder: (context, error, stackTrace) {
|
||||
// Si l'image ne charge pas, afficher une image par défaut
|
||||
return Image.asset('lib/assets/images/profile_picture.png', fit: BoxFit.cover);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Widget pour afficher l'icône de notifications avec un badge si nécessaire
|
||||
Widget _buildNotificationsIcon(BuildContext context, int notificationCount) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6.0),
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none, // Permet de positionner le badge en dehors des limites du Stack
|
||||
children: [
|
||||
const HomeContentScreen(), // Contenu de l'accueil.
|
||||
EventScreen(
|
||||
eventRemoteDataSource: widget.eventRemoteDataSource,
|
||||
userId: widget.userId,
|
||||
userName: widget.userName,
|
||||
userLastName: widget.userLastName,
|
||||
), // Écran des événements.
|
||||
const EstablishmentsScreen(), // Écran des établissements.
|
||||
const SocialScreen(), // Écran social.
|
||||
const ProfileScreen(), // Écran du profil.
|
||||
CircleAvatar(
|
||||
backgroundColor: AppColors.surface,
|
||||
radius: 18,
|
||||
child: IconButton(
|
||||
icon: const Icon(Icons.notifications, color: AppColors.darkOnPrimary, size: 20),
|
||||
onPressed: () {
|
||||
// Rediriger vers l'écran des notifications
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => const NotificationsScreen(),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
// Affiche le badge si le nombre de notifications est supérieur à 0
|
||||
if (notificationCount > 0)
|
||||
Positioned(
|
||||
right: -6,
|
||||
top: -6,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(2),
|
||||
decoration: const BoxDecoration(
|
||||
color: Colors.red, // Couleur du badge
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
constraints: const BoxConstraints(
|
||||
minWidth: 18,
|
||||
minHeight: 18,
|
||||
),
|
||||
child: Text(
|
||||
notificationCount > 99 ? '99+' : '$notificationCount', // Affiche "99+" si le nombre dépasse 99
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
backgroundColor: Colors.black, // Arrière-plan de l'écran en noir.
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildActionIcon(IconData iconData, String label, BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6.0), // Réduction de l'espacement
|
||||
child: CircleAvatar(
|
||||
backgroundColor: AppColors.surface,
|
||||
radius: 18, // Réduction de la taille des avatars
|
||||
child: IconButton(
|
||||
icon: Icon(iconData, color: AppColors.darkOnPrimary, size: 20), // Taille réduite de l'icône
|
||||
onPressed: () {
|
||||
_onMenuSelected(context, label);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,38 +1,82 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:google_maps_flutter/google_maps_flutter.dart';
|
||||
|
||||
class LocationPickerScreen extends StatelessWidget {
|
||||
const LocationPickerScreen({super.key});
|
||||
/// Écran pour la sélection d'une localisation sur une carte.
|
||||
/// L'utilisateur peut choisir un lieu en interagissant avec la carte Google Maps.
|
||||
/// Des logs permettent de tracer les actions comme la sélection et l'affichage de la carte.
|
||||
class LocationPickerScreen extends StatefulWidget {
|
||||
const LocationPickerScreen({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
_LocationPickerScreenState createState() => _LocationPickerScreenState();
|
||||
}
|
||||
|
||||
class _LocationPickerScreenState extends State<LocationPickerScreen> {
|
||||
LatLng _pickedLocation = const LatLng(37.7749, -122.4194); // Localisation par défaut (San Francisco)
|
||||
late GoogleMapController _mapController; // Contrôleur de la carte Google Maps
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
print('Affichage de l\'écran de sélection de localisation.');
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Sélectionnez une localisation'),
|
||||
backgroundColor: const Color(0xFF1E1E2C),
|
||||
title: const Text('Sélectionnez un lieu'),
|
||||
backgroundColor: Colors.blueAccent,
|
||||
),
|
||||
body: GoogleMap(
|
||||
initialCameraPosition: const CameraPosition(
|
||||
target: LatLng(48.8566, 2.3522), // Paris par défaut
|
||||
zoom: 12.0,
|
||||
),
|
||||
markers: <Marker>{
|
||||
Marker(
|
||||
markerId: const MarkerId('selectedLocation'),
|
||||
position: const LatLng(48.8566, 2.3522), // Position par défaut
|
||||
draggable: true,
|
||||
onDragEnd: (newPosition) {
|
||||
print('Nouvelle position sélectionnée: $newPosition');
|
||||
Navigator.of(context).pop(newPosition);
|
||||
},
|
||||
)
|
||||
},
|
||||
onTap: (position) {
|
||||
print('Position tapée: $position');
|
||||
Navigator.of(context).pop(position);
|
||||
},
|
||||
body: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: GoogleMap(
|
||||
initialCameraPosition: CameraPosition(
|
||||
target: _pickedLocation,
|
||||
zoom: 14,
|
||||
),
|
||||
onMapCreated: (controller) {
|
||||
_mapController = controller;
|
||||
print('Carte Google Maps créée.');
|
||||
},
|
||||
onTap: _selectLocation, // Sélection de la localisation sur la carte
|
||||
markers: {
|
||||
Marker(
|
||||
markerId: const MarkerId('pickedLocation'),
|
||||
position: _pickedLocation,
|
||||
),
|
||||
},
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: () {
|
||||
print('Lieu sélectionné : $_pickedLocation');
|
||||
Navigator.of(context).pop(_pickedLocation);
|
||||
},
|
||||
icon: const Icon(Icons.check),
|
||||
label: const Text('Confirmer la localisation'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
minimumSize: const Size(double.infinity, 50),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fonction pour gérer la sélection d'une localisation sur la carte.
|
||||
/// Lorsqu'une localisation est sélectionnée, elle est ajoutée à la carte et les logs sont mis à jour.
|
||||
void _selectLocation(LatLng position) {
|
||||
setState(() {
|
||||
_pickedLocation = position;
|
||||
});
|
||||
print('Localisation sélectionnée : $_pickedLocation');
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_mapController.dispose();
|
||||
print('Libération des ressources de la carte.');
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:afterwork/data/datasources/user_remote_data_source.dart';
|
||||
import 'package:afterwork/data/models/user_model.dart';
|
||||
import 'package:afterwork/presentation/screens/home/home_screen.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:afterwork/data/services/hash_password.dart';
|
||||
import 'package:afterwork/data/services/secure_storage.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/theme/theme_provider.dart';
|
||||
import '../../../data/datasources/event_remote_data_source.dart';
|
||||
import '../signup/SignUpScreen.dart';
|
||||
|
||||
/// Écran de connexion pour l'application AfterWork.
|
||||
/// Ce fichier contient des fonctionnalités comme la gestion de la connexion,
|
||||
/// l'authentification avec mot de passe en clair, la gestion des erreurs et un thème jour/nuit.
|
||||
class LoginScreen extends StatefulWidget {
|
||||
const LoginScreen({super.key});
|
||||
|
||||
@@ -18,87 +25,91 @@ class LoginScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStateMixin {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
String _userId = '';
|
||||
String _email = '';
|
||||
String _password = '';
|
||||
bool _isPasswordVisible = false;
|
||||
bool _isSubmitting = false;
|
||||
final _formKey = GlobalKey<FormState>(); // Clé pour valider le formulaire de connexion.
|
||||
|
||||
// Champs utilisateur
|
||||
String _email = ''; // Email de l'utilisateur
|
||||
String _password = ''; // Mot de passe de l'utilisateur
|
||||
|
||||
// É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();
|
||||
|
||||
late AnimationController _controller;
|
||||
late Animation<double> _buttonScaleAnimation;
|
||||
// Contrôleur pour le bouton de chargement
|
||||
final _btnController = LoadingButtonController();
|
||||
|
||||
// Contrôleur d'animation pour la transition des écrans
|
||||
late AnimationController _animationController;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = AnimationController(
|
||||
_animationController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
);
|
||||
_buttonScaleAnimation = Tween<double>(begin: 1.0, end: 1.1).animate(
|
||||
CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
|
||||
duration: const Duration(milliseconds: 500),
|
||||
);
|
||||
print("Contrôleur d'animation initialisé.");
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
_animationController.dispose();
|
||||
print("Ressources d'animation libérées.");
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Afficher/Masquer le mot de passe
|
||||
/// Fonction pour basculer la visibilité du mot de passe
|
||||
void _togglePasswordVisibility() {
|
||||
setState(() {
|
||||
_isPasswordVisible = !_isPasswordVisible;
|
||||
});
|
||||
print("Visibilité du mot de passe basculée: $_isPasswordVisible");
|
||||
}
|
||||
|
||||
/// Soumission du formulaire d'authentification
|
||||
void _submit() async {
|
||||
/// Fonction pour afficher un toast via FlutterToast
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
/// Fonction soumettre le formulaire
|
||||
Future<void> _submit() async {
|
||||
print("Tentative de soumission du formulaire de connexion.");
|
||||
|
||||
if (_formKey.currentState!.validate()) {
|
||||
setState(() {
|
||||
_isSubmitting = true;
|
||||
_showErrorMessage = false;
|
||||
});
|
||||
_formKey.currentState!.save();
|
||||
|
||||
print("===== DEBUT DE LA SOUMISSION DU FORMULAIRE =====");
|
||||
print("Email: $_email");
|
||||
print("Mot de passe: $_password");
|
||||
|
||||
try {
|
||||
print('Début de l\'authentification'); // Débogage
|
||||
_btnController.start();
|
||||
final UserModel user = await _userRemoteDataSource.authenticateUser(_email, _password);
|
||||
if (user == null) {
|
||||
throw Exception("L'utilisateur n'a pas été trouvé ou l'authentification a échoué.");
|
||||
}
|
||||
|
||||
// Hachage du mot de passe avec SHA-256
|
||||
String hashedPassword = hashPassword(_password);
|
||||
print("Mot de passe haché: $hashedPassword");
|
||||
|
||||
// Authentification via l'API avec un timeout
|
||||
UserModel user = await _userRemoteDataSource
|
||||
.authenticateUser(_email, hashedPassword, "unique_user_id")
|
||||
.timeout(
|
||||
Duration(seconds: 10),
|
||||
onTimeout: () {
|
||||
throw TimeoutException('Le temps de connexion a expiré. Veuillez réessayer.');
|
||||
},
|
||||
);
|
||||
|
||||
print('Connexion réussie : ${user.userId} - ${user.email}');
|
||||
|
||||
// Sauvegarde des données de l'utilisateur après authentification
|
||||
print("Utilisateur authentifié : ${user.userId}");
|
||||
await _secureStorage.saveUserId(user.userId);
|
||||
await _preferencesHelper.saveUserName(user.nom);
|
||||
await _preferencesHelper.saveUserLastName(user.prenoms);
|
||||
_showToast("Connexion réussie !");
|
||||
|
||||
print("===== SAUVEGARDE DES DONNÉES UTILISATEUR =====");
|
||||
print("User ID: ${user.userId}");
|
||||
print("User Name: ${user.nom}");
|
||||
print("User Last Name: ${user.prenoms}");
|
||||
|
||||
// Navigation vers l'écran d'accueil
|
||||
// Navigation vers la page d'accueil
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
@@ -107,44 +118,74 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
|
||||
userId: user.userId,
|
||||
userName: user.nom,
|
||||
userLastName: user.prenoms,
|
||||
userProfileImage: 'lib/assets/images/profile_picture.png',
|
||||
),
|
||||
),
|
||||
);
|
||||
print("===== NAVIGATION VERS HOME SCREEN =====");
|
||||
} catch (e) {
|
||||
print('Erreur lors de la connexion: $e');
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Erreur : ${e.toString()}')),
|
||||
);
|
||||
print("Erreur lors de l'authentification : $e");
|
||||
_btnController.error();
|
||||
_showToast("Erreur lors de la connexion : ${e.toString()}");
|
||||
setState(() {
|
||||
_showErrorMessage = true;
|
||||
});
|
||||
} finally {
|
||||
print('Fin du processus d\'authentification'); // Débogage
|
||||
_btnController.reset();
|
||||
setState(() {
|
||||
_isSubmitting = false;
|
||||
});
|
||||
}
|
||||
} else {
|
||||
print("===== FORMULAIRE NON VALIDE =====");
|
||||
print("Échec de validation du formulaire.");
|
||||
_btnController.reset();
|
||||
_showToast("Veuillez vérifier les informations saisies.");
|
||||
}
|
||||
}
|
||||
|
||||
@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;
|
||||
|
||||
return Scaffold(
|
||||
body: Stack(
|
||||
children: [
|
||||
// Arrière-plan avec dégradé
|
||||
Container(
|
||||
decoration: const BoxDecoration(
|
||||
AnimatedContainer(
|
||||
duration: const Duration(seconds: 3),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [Color(0xFF4A90E2), Color(0xFF9013FE)],
|
||||
colors: [
|
||||
theme.colorScheme.primary,
|
||||
theme.colorScheme.secondary
|
||||
],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
),
|
||||
),
|
||||
// Contenu de la page
|
||||
if (_isSubmitting)
|
||||
const Center(
|
||||
child: SpinKitFadingCircle(
|
||||
color: Colors.white,
|
||||
size: 50.0,
|
||||
),
|
||||
),
|
||||
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'}");
|
||||
},
|
||||
),
|
||||
),
|
||||
Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
@@ -153,148 +194,179 @@ class _LoginScreenState extends State<LoginScreen> with SingleTickerProviderStat
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
// Logo animé
|
||||
AnimatedBuilder(
|
||||
animation: _controller,
|
||||
builder: (context, child) {
|
||||
return Transform.scale(
|
||||
scale: _buttonScaleAnimation.value,
|
||||
child: child,
|
||||
);
|
||||
},
|
||||
child: GestureDetector(
|
||||
onTapDown: (_) => _controller.forward(),
|
||||
onTapUp: (_) => _controller.reverse(),
|
||||
child: Image.asset(
|
||||
'lib/assets/images/logo.png',
|
||||
height: size.height * 0.2,
|
||||
),
|
||||
),
|
||||
Image.asset(
|
||||
'lib/assets/images/logo.png',
|
||||
height: size.height * 0.25,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
const Text(
|
||||
Text(
|
||||
'Bienvenue sur AfterWork',
|
||||
style: TextStyle(
|
||||
fontSize: 26,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white,
|
||||
shadows: [
|
||||
Shadow(
|
||||
offset: Offset(0, 2),
|
||||
blurRadius: 6,
|
||||
color: Colors.black26,
|
||||
),
|
||||
],
|
||||
),
|
||||
style: theme.textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 40),
|
||||
// Champ Email
|
||||
TextFormField(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Email',
|
||||
filled: true,
|
||||
fillColor: Colors.white.withOpacity(0.1),
|
||||
labelStyle: const TextStyle(color: Colors.white),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(10.0),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
prefixIcon: const Icon(Icons.email, color: Colors.white),
|
||||
),
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
style: const TextStyle(color: Colors.white),
|
||||
_buildTextFormField(
|
||||
label: 'Email',
|
||||
icon: Icons.email,
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
print("Erreur: Le champ email est vide");
|
||||
print("Erreur : champ email vide.");
|
||||
return 'Veuillez entrer votre email';
|
||||
}
|
||||
if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
|
||||
print("Erreur: Le format de l'email est invalide");
|
||||
print("Erreur : email invalide.");
|
||||
return 'Veuillez entrer un email valide';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
onSaved: (value) {
|
||||
_email = value ?? ''; // Utiliser une chaîne vide si value est null
|
||||
print("Email sauvegardé: $_email");
|
||||
_email = value!;
|
||||
print("Email enregistré : $_email");
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
// Champ Mot de passe
|
||||
TextFormField(
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Mot de passe',
|
||||
filled: true,
|
||||
fillColor: Colors.white.withOpacity(0.1),
|
||||
labelStyle: const TextStyle(color: Colors.white),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(10.0),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
prefixIcon: const Icon(Icons.lock, color: Colors.white),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
_isPasswordVisible ? Icons.visibility : Icons.visibility_off,
|
||||
color: Colors.white),
|
||||
onPressed: _togglePasswordVisibility,
|
||||
),
|
||||
),
|
||||
_buildTextFormField(
|
||||
label: 'Mot de passe',
|
||||
icon: Icons.lock,
|
||||
obscureText: !_isPasswordVisible,
|
||||
style: const TextStyle(color: Colors.white),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
_isPasswordVisible
|
||||
? Icons.visibility
|
||||
: Icons.visibility_off,
|
||||
color: theme.iconTheme.color,
|
||||
),
|
||||
onPressed: _togglePasswordVisibility,
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
print("Erreur: Le champ mot de passe est vide");
|
||||
print("Erreur : champ mot de passe vide.");
|
||||
return 'Veuillez entrer votre mot de passe';
|
||||
}
|
||||
if (value.length < 6) {
|
||||
print("Erreur: Le mot de passe est trop court");
|
||||
print("Erreur : mot de passe trop court.");
|
||||
return 'Le mot de passe doit comporter au moins 6 caractères';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
onSaved: (value) {
|
||||
_password = value ?? ''; // Utiliser une chaîne vide si value est null
|
||||
print("Mot de passe sauvegardé: $_password");
|
||||
_password = value!;
|
||||
print("Mot de passe enregistré.");
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
// Bouton de connexion avec animation de soumission
|
||||
const SizedBox(height: 30),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
textStyle: const TextStyle(fontSize: 18),
|
||||
backgroundColor: _isSubmitting ? Colors.grey : Colors.blueAccent,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8.0),
|
||||
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,
|
||||
),
|
||||
),
|
||||
onPressed: _isSubmitting ? null : _submit,
|
||||
child: _isSubmitting
|
||||
? const CircularProgressIndicator(color: Colors.white)
|
||||
: const Text('Connexion'),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
// Lien pour s'inscrire
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
// Naviguer vers la page d'inscription
|
||||
print("Redirection vers la page d'inscription");
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => SignUpScreen(),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: const Text(
|
||||
child: Text(
|
||||
'Pas encore de compte ? Inscrivez-vous',
|
||||
style: TextStyle(color: Colors.white),
|
||||
style: theme.textTheme.bodyMedium!
|
||||
.copyWith(color: Colors.white70),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
print("Mot de passe oublié");
|
||||
},
|
||||
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 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);
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class NotificationsScreen extends StatelessWidget {
|
||||
const NotificationsScreen({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Notifications'),
|
||||
backgroundColor: Colors.blueAccent,
|
||||
),
|
||||
body: const Center(
|
||||
child: Text('Liste des notifications'),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,117 +1,147 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../core/constants/colors.dart';
|
||||
|
||||
class ProfileScreen extends StatelessWidget {
|
||||
const ProfileScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
print("Affichage de l'écran de profil.");
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Profil',
|
||||
style: TextStyle(
|
||||
color: Color(0xFF1DBF73), // Définit la couleur verte du texte
|
||||
),
|
||||
),
|
||||
backgroundColor: const Color(0xFF1E1E2C),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.settings, color: Colors.white),
|
||||
onPressed: () {
|
||||
// Naviguer vers la page des paramètres
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
children: [
|
||||
_buildUserInfoCard(),
|
||||
const SizedBox(height: 20),
|
||||
_buildEditOptionsCard(),
|
||||
const SizedBox(height: 20),
|
||||
_buildStatisticsSectionCard(),
|
||||
const SizedBox(height: 20),
|
||||
_buildExpandableSectionCard(
|
||||
title: 'Historique',
|
||||
icon: Icons.history,
|
||||
children: [
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.event_note,
|
||||
label: 'Historique des Événements',
|
||||
onTap: () {
|
||||
// Naviguer vers l'historique des événements
|
||||
},
|
||||
backgroundColor: AppColors.backgroundColor,
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
SliverAppBar(
|
||||
expandedHeight: 200.0,
|
||||
floating: false,
|
||||
pinned: true,
|
||||
backgroundColor: AppColors.darkPrimary,
|
||||
flexibleSpace: FlexibleSpaceBar(
|
||||
title: Text(
|
||||
'Profil',
|
||||
style: TextStyle(
|
||||
color: AppColors.accentColor,
|
||||
fontSize: 20.0,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.history,
|
||||
label: 'Historique des Publications',
|
||||
onTap: () {
|
||||
// Naviguer vers l'historique des publications
|
||||
},
|
||||
background: Image.asset(
|
||||
'lib/assets/images/profile_picture.png',
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.bookmark,
|
||||
label: 'Historique de Réservations',
|
||||
onTap: () {
|
||||
// Naviguer vers l'historique des réservations
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.settings, color: Colors.white),
|
||||
onPressed: () {
|
||||
print("Bouton des paramètres cliqué.");
|
||||
// Logique de navigation vers les paramètres
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
_buildExpandableSectionCard(
|
||||
title: 'Préférences et Paramètres',
|
||||
icon: Icons.settings,
|
||||
children: [
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.privacy_tip,
|
||||
label: 'Paramètres de confidentialité',
|
||||
onTap: () {
|
||||
// Naviguer vers les paramètres de confidentialité
|
||||
},
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.notifications,
|
||||
label: 'Notifications',
|
||||
onTap: () {
|
||||
// Naviguer vers les paramètres de notification
|
||||
},
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.language,
|
||||
label: 'Langue de l\'application',
|
||||
onTap: () {
|
||||
// Naviguer vers les paramètres de langue
|
||||
},
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.format_paint,
|
||||
label: 'Thème de l\'application',
|
||||
onTap: () {
|
||||
// Naviguer vers les paramètres de thème
|
||||
},
|
||||
),
|
||||
],
|
||||
SliverList(
|
||||
delegate: SliverChildListDelegate(
|
||||
[
|
||||
const SizedBox(height: 10),
|
||||
_buildUserInfoCard(),
|
||||
const SizedBox(height: 10),
|
||||
_buildEditOptionsCard(),
|
||||
const SizedBox(height: 10),
|
||||
_buildStatisticsSectionCard(),
|
||||
const SizedBox(height: 10),
|
||||
_buildExpandableSectionCard(
|
||||
title: 'Historique',
|
||||
icon: Icons.history,
|
||||
children: [
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.event_note,
|
||||
label: 'Historique des Événements',
|
||||
onTap: () {
|
||||
print("Accès à l'historique des événements.");
|
||||
// Logique de navigation vers l'historique des événements
|
||||
},
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.history,
|
||||
label: 'Historique des Publications',
|
||||
onTap: () {
|
||||
print("Accès à l'historique des publications.");
|
||||
// Logique de navigation vers l'historique des publications
|
||||
},
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.bookmark,
|
||||
label: 'Historique de Réservations',
|
||||
onTap: () {
|
||||
print("Accès à l'historique des réservations.");
|
||||
// Logique de navigation vers l'historique des réservations
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_buildExpandableSectionCard(
|
||||
title: 'Préférences et Paramètres',
|
||||
icon: Icons.settings,
|
||||
children: [
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.privacy_tip,
|
||||
label: 'Paramètres de confidentialité',
|
||||
onTap: () {
|
||||
print("Accès aux paramètres de confidentialité.");
|
||||
// Logique de navigation vers les paramètres de confidentialité
|
||||
},
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.notifications,
|
||||
label: 'Notifications',
|
||||
onTap: () {
|
||||
print("Accès aux paramètres de notifications.");
|
||||
// Logique de navigation vers les notifications
|
||||
},
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.language,
|
||||
label: 'Langue de l\'application',
|
||||
onTap: () {
|
||||
print("Accès aux paramètres de langue.");
|
||||
// Logique de navigation vers les paramètres de langue
|
||||
},
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.format_paint,
|
||||
label: 'Thème de l\'application',
|
||||
onTap: () {
|
||||
print("Accès aux paramètres de thème.");
|
||||
// Logique de navigation vers les paramètres de thème
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_buildSupportSectionCard(),
|
||||
const SizedBox(height: 10),
|
||||
_buildAccountDeletionCard(context),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
_buildSupportSectionCard(),
|
||||
const SizedBox(height: 20),
|
||||
_buildAccountDeletionCard(context),
|
||||
],
|
||||
),
|
||||
backgroundColor: const Color(0xFF1E1E2C),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildUserInfoCard() {
|
||||
return Card(
|
||||
color: const Color(0xFF292B37),
|
||||
color: AppColors.cardColor,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
|
||||
elevation: 2,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
children: [
|
||||
const CircleAvatar(
|
||||
CircleAvatar(
|
||||
radius: 50,
|
||||
backgroundImage: AssetImage('lib/assets/images/profile_picture.png'),
|
||||
backgroundColor: Colors.transparent,
|
||||
@@ -152,29 +182,33 @@ class ProfileScreen extends StatelessWidget {
|
||||
|
||||
Widget _buildEditOptionsCard() {
|
||||
return Card(
|
||||
color: const Color(0xFF292B37),
|
||||
color: AppColors.cardColor,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
|
||||
elevation: 2,
|
||||
child: Column(
|
||||
children: [
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.edit,
|
||||
label: 'Éditer le profil',
|
||||
onTap: () {
|
||||
// Naviguer vers la page d'édition de profil
|
||||
print("Édition du profil.");
|
||||
// Logique de navigation vers l'édition du profil
|
||||
},
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.camera_alt,
|
||||
label: 'Changer la photo de profil',
|
||||
onTap: () {
|
||||
// Naviguer vers la page de changement de photo de profil
|
||||
print("Changement de la photo de profil.");
|
||||
// Logique de changement de la photo de profil
|
||||
},
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.lock,
|
||||
label: 'Changer le mot de passe',
|
||||
onTap: () {
|
||||
// Naviguer vers la page de changement de mot de passe
|
||||
print("Changement du mot de passe.");
|
||||
// Logique de changement de mot de passe
|
||||
},
|
||||
),
|
||||
],
|
||||
@@ -184,8 +218,9 @@ class ProfileScreen extends StatelessWidget {
|
||||
|
||||
Widget _buildStatisticsSectionCard() {
|
||||
return Card(
|
||||
color: const Color(0xFF292B37),
|
||||
color: AppColors.cardColor,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
|
||||
elevation: 2,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
@@ -232,8 +267,9 @@ class ProfileScreen extends StatelessWidget {
|
||||
required List<Widget> children,
|
||||
}) {
|
||||
return Card(
|
||||
color: const Color(0xFF292B37),
|
||||
color: AppColors.cardColor,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
|
||||
elevation: 2,
|
||||
child: ExpansionTile(
|
||||
title: Text(
|
||||
title,
|
||||
@@ -243,9 +279,9 @@ class ProfileScreen extends StatelessWidget {
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
leading: Icon(icon, color: const Color(0xFF1DBF73)),
|
||||
iconColor: const Color(0xFF1DBF73),
|
||||
collapsedIconColor: const Color(0xFF1DBF73),
|
||||
leading: Icon(icon, color: AppColors.accentColor),
|
||||
iconColor: AppColors.accentColor,
|
||||
collapsedIconColor: AppColors.accentColor,
|
||||
children: children,
|
||||
),
|
||||
);
|
||||
@@ -253,8 +289,9 @@ class ProfileScreen extends StatelessWidget {
|
||||
|
||||
Widget _buildSupportSectionCard() {
|
||||
return Card(
|
||||
color: const Color(0xFF292B37),
|
||||
color: AppColors.cardColor,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
|
||||
elevation: 2,
|
||||
child: Column(
|
||||
children: [
|
||||
const Padding(
|
||||
@@ -272,21 +309,24 @@ class ProfileScreen extends StatelessWidget {
|
||||
icon: Icons.help,
|
||||
label: 'Support et Assistance',
|
||||
onTap: () {
|
||||
// Naviguer vers la page de support
|
||||
print("Accès au Support et Assistance.");
|
||||
// Logique de navigation vers le support
|
||||
},
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.article,
|
||||
label: 'Conditions d\'utilisation',
|
||||
onTap: () {
|
||||
// Naviguer vers les conditions d'utilisation
|
||||
print("Accès aux conditions d'utilisation.");
|
||||
// Logique de navigation vers les conditions d'utilisation
|
||||
},
|
||||
),
|
||||
_buildAnimatedListTile(
|
||||
icon: Icons.privacy_tip,
|
||||
label: 'Politique de confidentialité',
|
||||
onTap: () {
|
||||
// Naviguer vers la politique de confidentialité
|
||||
print("Accès à la politique de confidentialité.");
|
||||
// Logique de navigation vers la politique de confidentialité
|
||||
},
|
||||
),
|
||||
],
|
||||
@@ -296,8 +336,9 @@ class ProfileScreen extends StatelessWidget {
|
||||
|
||||
Widget _buildAccountDeletionCard(BuildContext context) {
|
||||
return Card(
|
||||
color: const Color(0xFF292B37),
|
||||
color: AppColors.cardColor,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
|
||||
elevation: 2,
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.delete, color: Colors.redAccent),
|
||||
title: const Text(
|
||||
@@ -307,7 +348,6 @@ class ProfileScreen extends StatelessWidget {
|
||||
onTap: () {
|
||||
_showDeleteConfirmationDialog(context);
|
||||
},
|
||||
hoverColor: Colors.red.withOpacity(0.1),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -317,7 +357,7 @@ class ProfileScreen extends StatelessWidget {
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
backgroundColor: const Color(0xFF1E1E2C),
|
||||
backgroundColor: AppColors.backgroundColor,
|
||||
title: const Text(
|
||||
'Confirmer la suppression',
|
||||
style: TextStyle(color: Colors.white),
|
||||
@@ -329,17 +369,17 @@ class ProfileScreen extends StatelessWidget {
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop(); // Fermer le popup
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
child: const Text(
|
||||
child: Text(
|
||||
'Annuler',
|
||||
style: TextStyle(color: Color(0xFF1DBF73)),
|
||||
style: TextStyle(color: AppColors.accentColor),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
// Logique de suppression du compte ici
|
||||
Navigator.of(context).pop(); // Fermer le popup après la suppression
|
||||
print("Suppression du compte confirmée.");
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
child: const Text(
|
||||
'Supprimer',
|
||||
@@ -362,12 +402,11 @@ class ProfileScreen extends StatelessWidget {
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
splashColor: Colors.blueAccent.withOpacity(0.2),
|
||||
child: ListTile(
|
||||
leading: Icon(icon, color: const Color(0xFF1DBF73)),
|
||||
leading: Icon(icon, color: AppColors.accentColor),
|
||||
title: Text(
|
||||
label,
|
||||
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
|
||||
),
|
||||
hoverColor: Colors.blue.withOpacity(0.1),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -378,7 +417,7 @@ class ProfileScreen extends StatelessWidget {
|
||||
required String value,
|
||||
}) {
|
||||
return ListTile(
|
||||
leading: Icon(icon, color: const Color(0xFF1DBF73)),
|
||||
leading: Icon(icon, color: AppColors.accentColor),
|
||||
title: Text(label, style: const TextStyle(color: Colors.white)),
|
||||
trailing: Text(
|
||||
value,
|
||||
@@ -388,7 +427,6 @@ class ProfileScreen extends StatelessWidget {
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
hoverColor: Colors.blue.withOpacity(0.1),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
396
lib/presentation/screens/signup/SignUpScreen.dart
Normal file
@@ -0,0 +1,396 @@
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,10 @@ import 'package:afterwork/data/datasources/event_remote_data_source.dart';
|
||||
@immutable
|
||||
abstract class EventEvent {}
|
||||
|
||||
class LoadEvents extends EventEvent {}
|
||||
class LoadEvents extends EventEvent {
|
||||
final String userId;
|
||||
LoadEvents(this.userId);
|
||||
}
|
||||
|
||||
class AddEvent extends EventEvent {
|
||||
final EventModel event;
|
||||
@@ -15,6 +18,18 @@ class AddEvent extends EventEvent {
|
||||
AddEvent(this.event);
|
||||
}
|
||||
|
||||
class CloseEvent extends EventEvent {
|
||||
final String eventId;
|
||||
|
||||
CloseEvent(this.eventId);
|
||||
}
|
||||
|
||||
class ReopenEvent extends EventEvent {
|
||||
final String eventId;
|
||||
|
||||
ReopenEvent(this.eventId);
|
||||
}
|
||||
|
||||
// Déclaration des états
|
||||
@immutable
|
||||
abstract class EventState {}
|
||||
@@ -35,39 +50,61 @@ class EventError extends EventState {
|
||||
EventError(this.message);
|
||||
}
|
||||
|
||||
// Bloc principal pour gérer la logique des événements
|
||||
// Bloc pour la gestion des événements
|
||||
class EventBloc extends Bloc<EventEvent, EventState> {
|
||||
final EventRemoteDataSource remoteDataSource;
|
||||
|
||||
EventBloc({required this.remoteDataSource}) : super(EventInitial()) {
|
||||
on<LoadEvents>(_onLoadEvents);
|
||||
on<AddEvent>(_onAddEvent);
|
||||
on<CloseEvent>(_onCloseEvent);
|
||||
on<ReopenEvent>(_onReopenEvent);
|
||||
}
|
||||
|
||||
// Gestion de l'événement LoadEvents
|
||||
// Gestion du chargement des événements
|
||||
Future<void> _onLoadEvents(LoadEvents event, Emitter<EventState> emit) async {
|
||||
emit(EventLoading());
|
||||
try {
|
||||
final events = await remoteDataSource.getAllEvents();
|
||||
emit(EventLoaded(events));
|
||||
print('Événements chargés avec succès.');
|
||||
} catch (e) {
|
||||
emit(EventError('Erreur lors du chargement des événements.'));
|
||||
print('Erreur lors du chargement des événements: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// Gestion de l'événement AddEvent
|
||||
// Gestion de l'ajout d'un nouvel événement
|
||||
Future<void> _onAddEvent(AddEvent event, Emitter<EventState> emit) async {
|
||||
emit(EventLoading());
|
||||
try {
|
||||
await remoteDataSource.createEvent(event.event);
|
||||
final events = await remoteDataSource.getAllEvents();
|
||||
emit(EventLoaded(events));
|
||||
print('Événement ajouté avec succès.');
|
||||
} catch (e) {
|
||||
emit(EventError('Erreur lors de l\'ajout de l\'événement.'));
|
||||
print('Erreur lors de l\'ajout de l\'événement: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// Gestion de la fermeture d'un événement
|
||||
Future<void> _onCloseEvent(CloseEvent event, Emitter<EventState> emit) async {
|
||||
emit(EventLoading());
|
||||
try {
|
||||
await remoteDataSource.closeEvent(event.eventId);
|
||||
final events = await remoteDataSource.getAllEvents();
|
||||
emit(EventLoaded(events));
|
||||
} catch (e) {
|
||||
emit(EventError('Erreur lors de la fermeture de l\'événement.'));
|
||||
}
|
||||
}
|
||||
|
||||
// Gestion de la réouverture d'un événement
|
||||
Future<void> _onReopenEvent(ReopenEvent event, Emitter<EventState> emit) async {
|
||||
emit(EventLoading());
|
||||
try {
|
||||
await remoteDataSource.reopenEvent(event.eventId);
|
||||
final events = await remoteDataSource.getAllEvents();
|
||||
emit(EventLoaded(events));
|
||||
} catch (e) {
|
||||
emit(EventError('Erreur lors de la réouverture de l\'événement.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,42 +2,52 @@ import 'package:afterwork/domain/entities/user.dart';
|
||||
import 'package:afterwork/domain/usecases/get_user.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
/// Bloc pour la gestion des événements et états liés à l'utilisateur.
|
||||
class UserBloc extends Bloc<UserEvent, UserState> {
|
||||
final GetUser getUser;
|
||||
|
||||
/// Constructeur avec injection du cas d'utilisation `GetUser`.
|
||||
UserBloc({required this.getUser}) : super(UserInitial());
|
||||
|
||||
@override
|
||||
Stream<UserState> mapEventToState(UserEvent event) async* {
|
||||
if (event is GetUserById) {
|
||||
yield UserLoading();
|
||||
final either = await getUser(event.id);
|
||||
|
||||
yield either.fold(
|
||||
(failure) => UserError(),
|
||||
(user) => UserLoaded(user: user),
|
||||
(failure) => UserError(),
|
||||
(user) => UserLoaded(user: user),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Classe abstraite représentant les événements liés à l'utilisateur.
|
||||
abstract class UserEvent {}
|
||||
|
||||
/// Événement pour récupérer un utilisateur par son ID.
|
||||
class GetUserById extends UserEvent {
|
||||
final String id;
|
||||
|
||||
GetUserById(this.id);
|
||||
}
|
||||
|
||||
/// Classe abstraite représentant les états possibles du BLoC utilisateur.
|
||||
abstract class UserState {}
|
||||
|
||||
/// État initial lorsque rien n'est encore chargé.
|
||||
class UserInitial extends UserState {}
|
||||
|
||||
/// État indiquant que les données utilisateur sont en cours de chargement.
|
||||
class UserLoading extends UserState {}
|
||||
|
||||
/// État indiquant que les données utilisateur ont été chargées avec succès.
|
||||
class UserLoaded extends UserState {
|
||||
final User user;
|
||||
|
||||
UserLoaded({required this.user});
|
||||
}
|
||||
|
||||
/// État indiquant qu'une erreur est survenue lors de la récupération des données utilisateur.
|
||||
class UserError extends UserState {}
|
||||
|
||||
23
lib/presentation/widgets/animated_action_button.dart
Normal file
@@ -0,0 +1,23 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class AnimatedActionButton extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final String label;
|
||||
|
||||
const AnimatedActionButton({
|
||||
super.key,
|
||||
required this.icon,
|
||||
required this.label,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
children: [
|
||||
Icon(icon, color: Colors.white, size: 30),
|
||||
const SizedBox(height: 5),
|
||||
Text(label, style: const TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
79
lib/presentation/widgets/create_story.dart
Normal file
@@ -0,0 +1,79 @@
|
||||
import 'dart:io';
|
||||
import 'package:camerawesome/camerawesome_plugin.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:logger/logger.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import '../../core/constants/colors.dart';
|
||||
|
||||
class CreateStoryPage extends StatefulWidget {
|
||||
const CreateStoryPage({super.key});
|
||||
|
||||
@override
|
||||
_CreateStoryPageState createState() => _CreateStoryPageState();
|
||||
}
|
||||
|
||||
class _CreateStoryPageState extends State<CreateStoryPage> {
|
||||
final Logger logger = Logger();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
extendBodyBehindAppBar: true, // Permet à l'AppBar de passer en mode transparent
|
||||
appBar: AppBar(
|
||||
title: const Text('Créer une nouvelle story'),
|
||||
backgroundColor: Colors.transparent, // Transparence
|
||||
elevation: 0, // Pas d'ombre pour l'en-tête
|
||||
leading: IconButton(
|
||||
icon: Icon(Icons.arrow_back, color: AppColors.onPrimary), // Couleur adaptative
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop(); // Bouton retour
|
||||
},
|
||||
),
|
||||
),
|
||||
body: Stack(
|
||||
children: [
|
||||
CameraAwesomeBuilder.awesome(
|
||||
saveConfig: SaveConfig.photoAndVideo(
|
||||
photoPathBuilder: (sensors) async {
|
||||
final sensor = sensors.first; // Utilisation du premier capteur
|
||||
final Directory extDir = await getTemporaryDirectory();
|
||||
final Directory testDir = await Directory('${extDir.path}/camerawesome').create(recursive: true);
|
||||
final String filePath = '${testDir.path}/${DateTime.now().millisecondsSinceEpoch}.jpg';
|
||||
return SingleCaptureRequest(filePath, sensor); // CaptureRequest pour la photo
|
||||
},
|
||||
videoPathBuilder: (sensors) async {
|
||||
final sensor = sensors.first; // Utilisation du premier capteur
|
||||
final Directory extDir = await getTemporaryDirectory();
|
||||
final Directory testDir = await Directory('${extDir.path}/camerawesome').create(recursive: true);
|
||||
final String filePath = '${testDir.path}/${DateTime.now().millisecondsSinceEpoch}.mp4';
|
||||
return SingleCaptureRequest(filePath, sensor); // CaptureRequest pour la vidéo
|
||||
},
|
||||
),
|
||||
sensorConfig: SensorConfig.single(
|
||||
sensor: Sensor.position(SensorPosition.back), // Configuration correcte du capteur
|
||||
),
|
||||
onMediaTap: (mediaCapture) async {
|
||||
final captureRequest = mediaCapture.captureRequest;
|
||||
|
||||
if (captureRequest is SingleCaptureRequest) {
|
||||
final filePath = captureRequest.path; // Accès au chemin de fichier
|
||||
if (filePath != null) {
|
||||
logger.i('Média capturé : $filePath');
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text('Média sauvegardé à $filePath'),
|
||||
backgroundColor: AppColors.accentColor, // Couleur adaptative du snack bar
|
||||
));
|
||||
} else {
|
||||
logger.e('Erreur : Aucun fichier capturé.');
|
||||
}
|
||||
} else {
|
||||
logger.e('Erreur : Capture non reconnue.');
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ class CustomDrawer extends StatelessWidget {
|
||||
child: ListView(
|
||||
padding: EdgeInsets.zero,
|
||||
children: <Widget>[
|
||||
DrawerHeader(
|
||||
const DrawerHeader(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blueAccent,
|
||||
),
|
||||
|
||||
58
lib/presentation/widgets/event_list.dart
Normal file
@@ -0,0 +1,58 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:afterwork/data/models/event_model.dart';
|
||||
|
||||
import '../screens/event/event_card.dart';
|
||||
|
||||
class EventList extends StatelessWidget {
|
||||
final List<EventModel> events;
|
||||
|
||||
const EventList({Key? key, required this.events}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView.builder(
|
||||
itemCount: events.length,
|
||||
itemBuilder: (context, index) {
|
||||
final event = events[index];
|
||||
|
||||
return EventCard(
|
||||
event: event,
|
||||
userId: 'user_id_here', // Vous pouvez passer l'ID réel de l'utilisateur connecté
|
||||
userName: 'John', // Vous pouvez passer le prénom réel de l'utilisateur
|
||||
userLastName: 'Doe', // Vous pouvez passer le nom réel de l'utilisateur
|
||||
onReact: () => _handleReact(event),
|
||||
onComment: () => _handleComment(event),
|
||||
onShare: () => _handleShare(event),
|
||||
onParticipate: () => _handleParticipate(event),
|
||||
onCloseEvent: () => _handleCloseEvent(event),
|
||||
onReopenEvent: () => _handleReopenEvent(event),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Gestion des actions
|
||||
void _handleReact(EventModel event) {
|
||||
print('Réaction ajoutée à l\'événement ${event.title}');
|
||||
}
|
||||
|
||||
void _handleComment(EventModel event) {
|
||||
print('Commentaire ajouté à l\'événement ${event.title}');
|
||||
}
|
||||
|
||||
void _handleShare(EventModel event) {
|
||||
print('Événement partagé : ${event.title}');
|
||||
}
|
||||
|
||||
void _handleParticipate(EventModel event) {
|
||||
print('Participation confirmée à l\'événement ${event.title}');
|
||||
}
|
||||
|
||||
void _handleCloseEvent(EventModel event) {
|
||||
print('Événement ${event.title} fermé');
|
||||
}
|
||||
|
||||
void _handleReopenEvent(EventModel event) {
|
||||
print('Événement ${event.title} réouvert');
|
||||
}
|
||||
}
|
||||
62
lib/presentation/widgets/friend_suggestions.dart
Normal file
@@ -0,0 +1,62 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class FriendSuggestions extends StatelessWidget {
|
||||
final Size size;
|
||||
|
||||
const FriendSuggestions({required this.size, Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
children: List.generate(3, (index) {
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 20),
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
width: size.width,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey[850],
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.3),
|
||||
blurRadius: 6,
|
||||
offset: const Offset(0, 3),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const CircleAvatar(
|
||||
radius: 30,
|
||||
backgroundImage: AssetImage('lib/assets/images/friend_placeholder.png'),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
const Expanded(
|
||||
child: Text(
|
||||
'Nom d\'utilisateur',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
print('Ajouter comme ami');
|
||||
},
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.teal,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
child: const Text('Ajouter'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
63
lib/presentation/widgets/group_list.dart
Normal file
@@ -0,0 +1,63 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class GroupList extends StatelessWidget {
|
||||
final Size size;
|
||||
|
||||
const GroupList({required this.size, Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
children: List.generate(3, (index) {
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 20),
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
width: size.width,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey[850],
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.3),
|
||||
blurRadius: 6,
|
||||
offset: const Offset(0, 3),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
const CircleAvatar(
|
||||
radius: 30,
|
||||
backgroundImage: AssetImage('lib/assets/images/group_placeholder.png'),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
const Expanded(
|
||||
child: Text(
|
||||
'Club des Amateurs de Cinéma',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
print('Rejoindre le groupe');
|
||||
},
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.blueAccent,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
child: const Text('Rejoindre'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
58
lib/presentation/widgets/popular_activity_list.dart
Normal file
@@ -0,0 +1,58 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class PopularActivityList extends StatelessWidget {
|
||||
final Size size;
|
||||
|
||||
const PopularActivityList({required this.size, Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SizedBox(
|
||||
height: 200,
|
||||
child: ListView.separated(
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: 3,
|
||||
separatorBuilder: (context, index) => const SizedBox(width: 15),
|
||||
itemBuilder: (context, index) {
|
||||
return Container(
|
||||
width: size.width * 0.8,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey[800],
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
image: const DecorationImage(
|
||||
image: AssetImage('lib/assets/images/activity_placeholder.png'),
|
||||
fit: BoxFit.cover,
|
||||
colorFilter: ColorFilter.mode(Colors.black38, BlendMode.darken),
|
||||
),
|
||||
),
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.all(12.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Soirée Stand-up Comedy',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 5),
|
||||
Text(
|
||||
'Vendredi, 20h00',
|
||||
style: TextStyle(
|
||||
color: Colors.white70,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
35
lib/presentation/widgets/quick_action_button.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class QuickActionButton extends StatelessWidget {
|
||||
final String label;
|
||||
final IconData icon;
|
||||
final Color color;
|
||||
final double fontSize; // Ajout d'un paramètre pour personnaliser la taille du texte
|
||||
|
||||
const QuickActionButton({
|
||||
required this.label,
|
||||
required this.icon,
|
||||
required this.color,
|
||||
this.fontSize = 14, // Valeur par défaut
|
||||
Key? key,
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
children: [
|
||||
CircleAvatar(
|
||||
radius: 30,
|
||||
backgroundColor: color.withOpacity(0.2),
|
||||
child: Icon(icon, color: color, size: 28),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(color: Colors.white, fontSize: fontSize), // Utilisation de fontSize
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
66
lib/presentation/widgets/recommended_event_list.dart
Normal file
@@ -0,0 +1,66 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class RecommendedEventList extends StatelessWidget {
|
||||
final Size size;
|
||||
|
||||
const RecommendedEventList({required this.size, Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SizedBox(
|
||||
height: 240,
|
||||
child: ListView.separated(
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: 3, // Nombre d'événements fictifs
|
||||
separatorBuilder: (context, index) => const SizedBox(width: 15),
|
||||
itemBuilder: (context, index) {
|
||||
return AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 300),
|
||||
width: size.width * 0.8,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey[800],
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
image: const DecorationImage(
|
||||
image: AssetImage('lib/assets/images/event_placeholder.png'),
|
||||
fit: BoxFit.cover,
|
||||
colorFilter: ColorFilter.mode(Colors.black38, BlendMode.darken),
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.5),
|
||||
blurRadius: 6,
|
||||
offset: const Offset(0, 3),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: const Padding(
|
||||
padding: EdgeInsets.all(12.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Concert de Jazz',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 5),
|
||||
Text(
|
||||
'Samedi, 18h00',
|
||||
style: TextStyle(
|
||||
color: Colors.white70,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
32
lib/presentation/widgets/section_header.dart
Normal file
@@ -0,0 +1,32 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class SectionHeader extends StatelessWidget {
|
||||
final String title;
|
||||
final IconData icon;
|
||||
final TextStyle? textStyle; // Ajout de la possibilité de personnaliser le style du texte
|
||||
|
||||
const SectionHeader({
|
||||
required this.title,
|
||||
required this.icon,
|
||||
this.textStyle, // Paramètre optionnel
|
||||
Key? key,
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: textStyle ?? const TextStyle( // Utilisation du style fourni ou d'un style par défaut
|
||||
color: Colors.white,
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Icon(icon, color: Colors.white),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
112
lib/presentation/widgets/story_detail.dart
Normal file
@@ -0,0 +1,112 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:afterwork/presentation/widgets/story_video_player.dart';
|
||||
import '../../../core/utils/calculate_time_ago.dart';
|
||||
import 'animated_action_button.dart';
|
||||
|
||||
class StoryDetail extends StatefulWidget {
|
||||
final String username;
|
||||
final DateTime publicationDate;
|
||||
final String mediaUrl;
|
||||
final String userImage;
|
||||
final bool isVideo;
|
||||
|
||||
const StoryDetail({
|
||||
super.key,
|
||||
required this.username,
|
||||
required this.publicationDate,
|
||||
required this.mediaUrl,
|
||||
required this.userImage,
|
||||
required this.isVideo,
|
||||
});
|
||||
|
||||
@override
|
||||
StoryDetailState createState() => StoryDetailState();
|
||||
}
|
||||
|
||||
class StoryDetailState extends State<StoryDetail> {
|
||||
late Offset _startDragOffset;
|
||||
late Offset _currentDragOffset;
|
||||
bool _isDragging = false;
|
||||
|
||||
// Gestion du swipe vertical pour fermer la story
|
||||
void _onVerticalDragStart(DragStartDetails details) {
|
||||
_startDragOffset = details.globalPosition;
|
||||
}
|
||||
|
||||
void _onVerticalDragUpdate(DragUpdateDetails details) {
|
||||
_currentDragOffset = details.globalPosition;
|
||||
if (_currentDragOffset.dy - _startDragOffset.dy > 100) {
|
||||
setState(() {
|
||||
_isDragging = true;
|
||||
});
|
||||
Navigator.pop(context);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.black,
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
iconTheme: const IconThemeData(color: Colors.white),
|
||||
),
|
||||
body: GestureDetector(
|
||||
onVerticalDragStart: _onVerticalDragStart,
|
||||
onVerticalDragUpdate: _onVerticalDragUpdate,
|
||||
child: Stack(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: AnimatedOpacity(
|
||||
opacity: _isDragging ? 0.5 : 1.0,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
child: widget.isVideo
|
||||
? StoryVideoPlayer(mediaUrl: widget.mediaUrl)
|
||||
: Image.asset(widget.mediaUrl, fit: BoxFit.cover),
|
||||
),
|
||||
),
|
||||
// Informations sur l'utilisateur
|
||||
Positioned(
|
||||
top: 40,
|
||||
left: 20,
|
||||
child: Row(
|
||||
children: [
|
||||
CircleAvatar(radius: 32, backgroundImage: AssetImage(widget.userImage)),
|
||||
const SizedBox(width: 12),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
widget.username,
|
||||
style: const TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
|
||||
),
|
||||
Text(
|
||||
'Il y a ${calculateTimeAgo(widget.publicationDate)}',
|
||||
style: const TextStyle(color: Colors.white70, fontSize: 14),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Boutons d'actions flottants à droite
|
||||
const Positioned(
|
||||
right: 20,
|
||||
bottom: 100,
|
||||
child: Column(
|
||||
children: [
|
||||
AnimatedActionButton(icon: Icons.favorite_border, label: 'J\'aime'),
|
||||
SizedBox(height: 20),
|
||||
AnimatedActionButton(icon: Icons.comment, label: 'Commenter'),
|
||||
SizedBox(height: 20),
|
||||
AnimatedActionButton(icon: Icons.share, label: 'Partager'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
194
lib/presentation/widgets/story_section.dart
Normal file
@@ -0,0 +1,194 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:logger/logger.dart';
|
||||
import '../../core/constants/colors.dart';
|
||||
import '../../core/utils/calculate_time_ago.dart';
|
||||
import 'story_detail.dart';
|
||||
import 'create_story.dart';
|
||||
|
||||
/// La classe StorySection représente la section des stories dans l'interface.
|
||||
/// Elle affiche une liste horizontale de stories et permet à l'utilisateur d'ajouter une nouvelle story.
|
||||
/// Les logs sont utilisés pour tracer chaque action réalisée dans l'interface.
|
||||
class StorySection extends StatelessWidget {
|
||||
final Size size;
|
||||
final Logger logger = Logger(); // Logger pour tracer les événements et actions
|
||||
|
||||
StorySection({required this.size, super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
logger.i('Construction de la section des stories');
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: SizedBox(
|
||||
height: size.height / 4.5, // Hauteur ajustée pour éviter le débordement
|
||||
child: ListView.separated(
|
||||
scrollDirection: Axis.horizontal,
|
||||
itemCount: 6, // Nombre de stories à afficher
|
||||
separatorBuilder: (context, index) => const SizedBox(width: 8),
|
||||
itemBuilder: (context, index) {
|
||||
if (index == 0) return _buildAddStoryCard(context);
|
||||
|
||||
DateTime publicationDate = DateTime.now().subtract(Duration(hours: (index - 1) * 6));
|
||||
logger.i('Affichage de la story $index avec la date $publicationDate');
|
||||
|
||||
return GestureDetector(
|
||||
onTap: () {
|
||||
logger.i('Clic sur la story $index, affichage du détail');
|
||||
Navigator.push(
|
||||
context,
|
||||
PageRouteBuilder(
|
||||
pageBuilder: (context, animation, secondaryAnimation) => FadeTransition(
|
||||
opacity: animation,
|
||||
child: StoryDetail(
|
||||
username: 'Utilisateur ${index - 1}',
|
||||
publicationDate: publicationDate,
|
||||
mediaUrl: 'https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4',
|
||||
userImage: 'lib/assets/images/user_placeholder.png',
|
||||
isVideo: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: _buildStoryCard(index, publicationDate),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit une carte de story à partir de l'index et de la date de publication.
|
||||
Widget _buildStoryCard(int index, DateTime publicationDate) {
|
||||
return Column( // Utilisation de Column sans Expanded pour éviter les erreurs
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Container(
|
||||
width: size.width / 4.5,
|
||||
height: size.height / 5.5, // Hauteur ajustée pour éviter le dépassement
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.cardColor, // Utilisation des couleurs automatiques pour le fond des cartes
|
||||
borderRadius: BorderRadius.circular(20), // Bords arrondis à 20 pixels
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.1),
|
||||
blurRadius: 6,
|
||||
offset: const Offset(0, 3),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
Positioned.fill(child: _buildGradientOverlay()),
|
||||
Positioned(top: 6, right: 6, child: _buildAvatar(index)),
|
||||
Positioned(bottom: 10, left: 10, child: _buildUsername(index)),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4), // Espace entre la carte et la date
|
||||
_buildPublicationDate(publicationDate),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit un overlay en dégradé pour la story.
|
||||
Widget _buildGradientOverlay() {
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [Colors.black.withOpacity(0.4), Colors.transparent],
|
||||
begin: Alignment.bottomCenter,
|
||||
end: Alignment.topCenter,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(20), // Assure que l'overlay suit les bords arrondis
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit l'avatar de l'utilisateur pour la story.
|
||||
Widget _buildAvatar(int index) {
|
||||
return Hero(
|
||||
tag: 'avatar-$index',
|
||||
child: CircleAvatar(
|
||||
radius: 16,
|
||||
backgroundColor: Colors.grey.withOpacity(0.2),
|
||||
child: const CircleAvatar(
|
||||
radius: 14,
|
||||
backgroundImage: AssetImage('lib/assets/images/user_placeholder.png'),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit le nom d'utilisateur affiché sous la story.
|
||||
Widget _buildUsername(int index) {
|
||||
return Text(
|
||||
'Utilisateur ${index - 1}',
|
||||
style: TextStyle(
|
||||
fontFamily: 'Montserrat',
|
||||
color: AppColors.textPrimary, // Texte principal avec couleur dynamique
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Affiche la date de publication sous forme relative ("il y a X heures").
|
||||
Widget _buildPublicationDate(DateTime publicationDate) {
|
||||
return Text(
|
||||
'Il y a ${calculateTimeAgo(publicationDate)}',
|
||||
style: TextStyle(
|
||||
color: AppColors.textSecondary, // Texte secondaire avec couleur dynamique
|
||||
fontSize: 11,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construit une carte spéciale pour ajouter une nouvelle story.
|
||||
Widget _buildAddStoryCard(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onTap: () {
|
||||
logger.i('Clic sur l\'ajout d\'une nouvelle story');
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(builder: (context) => const CreateStoryPage()),
|
||||
);
|
||||
},
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Container(
|
||||
width: size.width / 4.5,
|
||||
height: size.height / 5.5, // Hauteur ajustée pour éviter le dépassement
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.cardColor, // Utilisation des couleurs automatiques pour le fond des cartes
|
||||
borderRadius: BorderRadius.circular(20), // Bords arrondis à 20 pixels
|
||||
border: Border.all(color: AppColors.accentColor.withOpacity(0.3), width: 2),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.1),
|
||||
blurRadius: 6,
|
||||
offset: const Offset(0, 3),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Center(
|
||||
child: Icon(
|
||||
Icons.add_circle_outline,
|
||||
color: AppColors.accentColor, // Utilisation des couleurs automatiques pour les icônes
|
||||
size: 40,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Créer une story',
|
||||
style: TextStyle(color: AppColors.textSecondary, fontSize: 13), // Texte secondaire avec couleur dynamique
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
75
lib/presentation/widgets/story_video_player.dart
Normal file
@@ -0,0 +1,75 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:video_player/video_player.dart'; // Pour la lecture des vidéos
|
||||
|
||||
class StoryVideoPlayer extends StatefulWidget {
|
||||
final String mediaUrl;
|
||||
|
||||
const StoryVideoPlayer({super.key, required this.mediaUrl});
|
||||
|
||||
@override
|
||||
StoryVideoPlayerState createState() => StoryVideoPlayerState(); // Classe publique
|
||||
}
|
||||
|
||||
class StoryVideoPlayerState extends State<StoryVideoPlayer> {
|
||||
VideoPlayerController? _videoPlayerController;
|
||||
bool _loadingError = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initializeVideoPlayer();
|
||||
}
|
||||
|
||||
void _initializeVideoPlayer() async {
|
||||
_videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(widget.mediaUrl));
|
||||
|
||||
try {
|
||||
await _videoPlayerController!.initialize();
|
||||
setState(() {
|
||||
_loadingError = false;
|
||||
_videoPlayerController!.play();
|
||||
});
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_loadingError = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_videoPlayerController?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_loadingError) {
|
||||
return _buildRetryUI();
|
||||
} else if (_videoPlayerController != null && _videoPlayerController!.value.isInitialized) {
|
||||
return VideoPlayer(_videoPlayerController!);
|
||||
} else {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildRetryUI() {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text('Problème de connexion ou de chargement', style: TextStyle(color: Colors.white)),
|
||||
const SizedBox(height: 20),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_initializeVideoPlayer();
|
||||
});
|
||||
},
|
||||
child: const Text('Réessayer'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||