Refactoring + Version améliorée

This commit is contained in:
DahoudG
2024-09-25 21:28:04 +00:00
parent 6b12cfeb41
commit 8e625c1080
28 changed files with 1113 additions and 261 deletions

View File

@@ -1,110 +1,118 @@
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'dart:io';
/// 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 {
import '../../widgets/category_field.dart';
import '../../widgets/date_picker.dart';
import '../../widgets/description_field.dart';
import '../../widgets/link_field.dart';
import '../../widgets/location_field.dart';
import '../../widgets/submit_button.dart';
import '../../widgets/title_field.dart';
import '../../widgets/image_preview_picker.dart';
class AddEventPage extends StatefulWidget {
final String userId;
final String userName;
final String userLastName;
const AddEventDialog({
Key? key,
const AddEventPage({
super.key,
required this.userId,
required this.userName,
required this.userLastName,
}) : super(key: key);
});
@override
_AddEventDialogState createState() => _AddEventDialogState();
_AddEventPageState createState() => _AddEventPageState();
}
class _AddEventDialogState extends State<AddEventDialog> {
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
class _AddEventPageState extends State<AddEventPage> {
final _formKey = GlobalKey<FormState>(); // Form key for validation
String _title = '';
String _description = '';
DateTime? _selectedDate;
String _location = 'Abidjan';
String _category = '';
String _link = '';
LatLng? _selectedLatLng = const LatLng(5.348722, -3.985038); // Default coordinates
File? _selectedImageFile; // Store the selected image
@override
Widget build(BuildContext context) {
print("Affichage du dialogue d'ajout d'événement.");
return AlertDialog(
title: const Text('Ajouter un événement'),
content: Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// 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]),
),
],
),
),
actions: [
// Bouton pour annuler l'ajout de l'événement
TextButton(
return Scaffold(
appBar: AppBar(
title: const Text('Ajouter un événement'),
backgroundColor: const Color(0xFF1E1E2C),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
print("L'utilisateur a annulé l'ajout de l'événement.");
Navigator.of(context).pop();
},
child: const Text('Annuler'),
),
// 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,
});
}
},
child: const Text('Ajouter'),
),
],
),
backgroundColor: const Color(0xFF1E1E2C),
body: Column(
children: [
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ImagePreviewPicker(
onImagePicked: (File? imageFile) {
setState(() {
_selectedImageFile = imageFile;
});
},
),
const SizedBox(height: 20),
TitleField(onSaved: (value) => setState(() => _title = value ?? '')),
const SizedBox(height: 12),
DescriptionField(onSaved: (value) => setState(() => _description = value ?? '')),
const SizedBox(height: 12),
DatePickerField(
selectedDate: _selectedDate,
onDatePicked: (picked) => setState(() {
_selectedDate = picked;
}),
),
const SizedBox(height: 12),
LocationField(
location: _location,
selectedLatLng: _selectedLatLng,
onLocationPicked: (pickedLocation) => setState(() {
_selectedLatLng = pickedLocation;
_location = '${pickedLocation?.latitude}, ${pickedLocation?.longitude}';
}),
),
const SizedBox(height: 12),
CategoryField(onSaved: (value) => setState(() => _category = value ?? '')),
const SizedBox(height: 12),
LinkField(onSaved: (value) => setState(() => _link = value ?? '')),
],
),
),
),
),
// Bouton en bas de l'écran
Padding(
padding: const EdgeInsets.all(16.0),
child: SubmitButton(
onPressed: () async {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
// Logic to add the event goes here
}
},
),
),
],
),
);
}
/// 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;
}
}

View File

@@ -1,19 +1,25 @@
import 'package:flutter/material.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.
import '../../../data/models/event_model.dart';
import '../../widgets/event_header.dart';
import '../../widgets/event_image.dart';
import '../../widgets/event_interaction_row.dart';
import '../../widgets/event_status_badge.dart';
import '../../widgets/swipe_background.dart';
class EventCard extends StatelessWidget {
final EventModel event;
final String userId;
final String userName;
final String userLastName;
final String status;
final VoidCallback onReact;
final VoidCallback onComment;
final VoidCallback onShare;
final VoidCallback onParticipate;
final VoidCallback onCloseEvent;
final VoidCallback onReopenEvent;
final Function onRemoveEvent;
const EventCard({
Key? key,
@@ -21,152 +27,93 @@ class EventCard extends StatelessWidget {
required this.userId,
required this.userName,
required this.userLastName,
required this.status,
required this.onReact,
required this.onComment,
required this.onShare,
required this.onParticipate,
required this.onCloseEvent,
required this.onReopenEvent,
required this.onRemoveEvent,
}) : super(key: key);
@override
Widget build(BuildContext context) {
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: [
_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(),
],
),
final GlobalKey menuKey = GlobalKey();
return Dismissible(
key: ValueKey(event.id),
direction: event.status == 'fermé'
? DismissDirection.startToEnd
: DismissDirection.endToStart,
onDismissed: (direction) {
if (event.status == 'fermé') {
onReopenEvent();
} else {
onCloseEvent();
onRemoveEvent(event.id);
}
},
background: SwipeBackground(
color: event.status == 'fermé' ? Colors.green : Colors.red,
icon: event.status == 'fermé' ? Icons.lock_open : Icons.lock,
label: event.status == 'fermé' ? 'Rouvrir' : 'Fermer',
),
);
}
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 DateFormatter pour afficher une date lisible si elle est valide
String formattedDate = eventDate != null ? DateFormatter.formatDate(eventDate) : 'Date inconnue';
return Row(
children: [
CircleAvatar(backgroundImage: NetworkImage(event.imageUrl ?? 'lib/assets/images/placeholder.png')),
const SizedBox(width: 10),
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: () {
// 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.
},
),
],
);
}
Widget _buildEventImage() {
return ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image.network(
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
}
),
);
}
Widget _buildInteractionRow() {
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),
],
);
}
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),
),
);
}
// 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,
child: 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: [
EventHeader(
userName: userName,
userLastName: userLastName,
eventDate: event.startDate,
imageUrl: event.imageUrl,
menuKey: menuKey,
menuContext: context,
location: event.location,
),
const Divider(color: Colors.white24),
Row(
children: [
const Spacer(), // Pusher le badge statut à la droite.
EventStatusBadge(status: status),
],
),
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),
EventImage(imageUrl: event.imageUrl),
const Divider(color: Colors.white24),
EventInteractionRow(
onReact: onReact,
onComment: onComment,
onShare: onShare,
reactionsCount: event.reactionsCount,
commentsCount: event.commentsCount,
sharesCount: event.sharesCount,
),
],
),
),
event.status == 'closed'
? ElevatedButton(
onPressed: onReopenEvent,
child: const Text('Rouvrir l\'événement'),
)
: ElevatedButton(
onPressed: onCloseEvent,
child: const Text('Fermer l\'événement'),
),
],
),
);
}
}

View File

@@ -2,8 +2,8 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:afterwork/data/models/event_model.dart';
import 'package:afterwork/presentation/screens/event/event_card.dart';
import '../../state_management/event_bloc.dart';
import '../dialogs/add_event_dialog.dart';
import '../../state_management/event_bloc.dart';
class EventScreen extends StatefulWidget {
final String userId;
@@ -43,25 +43,18 @@ class _EventScreenState extends State<EventScreen> {
actions: [
IconButton(
icon: const Icon(Icons.add_circle_outline, size: 28, color: Color(0xFF1DBF73)),
onPressed: () async {
final eventData = await showDialog<Map<String, dynamic>>(
context: context,
builder: (BuildContext context) {
return AddEventDialog(
onPressed: () {
// Naviguer vers une nouvelle page pour ajouter un événement
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddEventPage(
userId: widget.userId,
userName: widget.userName,
userLastName: widget.userLastName,
);
},
),
),
);
if (eventData != null) {
// 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 !')),
);
}
},
),
],
@@ -92,7 +85,17 @@ class _EventScreenState extends State<EventScreen> {
onParticipate: () => _onParticipate(event.id),
onCloseEvent: () => _onCloseEvent(event.id),
onReopenEvent: () => _onReopenEvent(event.id),
onRemoveEvent: (String eventId) {
// Retirer l'événement localement après la fermeture
setState(() {
// Logique pour retirer l'événement de la liste localement
// Par exemple, vous pouvez appeler le bloc ou mettre à jour l'état local ici
context.read<EventBloc>().add(RemoveEvent(eventId));
});
},
status: event.status,
);
},
);
} else if (state is EventError) {

View File

@@ -3,7 +3,6 @@ import '../../../core/constants/colors.dart'; // Importez les couleurs dynamique
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';