Files
TravelMate/lib/components/home/create_trip_content.dart
Dayron e3dad39c4f feat: Add TripImageService for automatic trip image management
- Implemented TripImageService to load missing images for trips, reload images, and clean up unused images.
- Added functionality to get image statistics and clean up duplicate images.
- Created utility scripts for manual image cleanup and diagnostics in Firebase Storage.
- Introduced tests for image loading optimization and photo quality algorithms.
- Updated dependencies in pubspec.yaml and pubspec.lock for image handling.
2025-11-03 14:33:58 +01:00

1068 lines
36 KiB
Dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:travel_mate/models/trip.dart';
import 'package:travel_mate/services/error_service.dart';
import '../../blocs/user/user_bloc.dart';
import '../../blocs/user/user_state.dart' as user_state;
import '../../blocs/trip/trip_bloc.dart';
import '../../blocs/trip/trip_event.dart';
import '../../blocs/trip/trip_state.dart';
import '../../blocs/group/group_bloc.dart';
import '../../blocs/group/group_event.dart';
import '../../blocs/account/account_bloc.dart';
import '../../blocs/account/account_event.dart';
import '../../models/account.dart';
import '../../models/group.dart';
import '../../models/group_member.dart';
import '../../services/user_service.dart';
import '../../repositories/group_repository.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../../services/place_image_service.dart';
/// Create trip content widget for trip creation and editing functionality.
///
/// This widget provides a comprehensive form interface for creating new trips
/// or editing existing ones. Key features include:
/// - Trip creation with validation
/// - Location search with autocomplete
/// - Date selection for trip duration
/// - Budget planning and management
/// - Group creation and member management
/// - Account setup for expense tracking
/// - Integration with mapping services for location selection
///
/// The widget handles both creation and editing modes based on the
/// provided tripToEdit parameter.
class CreateTripContent extends StatefulWidget {
/// Optional trip to edit. If null, creates a new trip
final Trip? tripToEdit;
/// Creates a create trip content widget.
///
/// Args:
/// [tripToEdit]: Optional trip to edit. If provided, the form will
/// be populated with existing trip data for editing
const CreateTripContent({
super.key,
this.tripToEdit,
});
@override
State<CreateTripContent> createState() => _CreateTripContentState();
}
class _CreateTripContentState extends State<CreateTripContent> {
/// Service for handling and displaying errors
final _errorService = ErrorService();
/// Form validation key
final _formKey = GlobalKey<FormState>();
/// Text controllers for form fields
final _titleController = TextEditingController();
final _descriptionController = TextEditingController();
final _locationController = TextEditingController();
final _budgetController = TextEditingController();
final _participantController = TextEditingController();
/// Services for user and group operations
final _userService = UserService();
final _groupRepository = GroupRepository();
final _placeImageService = PlaceImageService();
/// Trip date variables
DateTime? _startDate;
DateTime? _endDate;
/// Loading and state management variables
bool _isLoading = false;
String? _createdTripId;
String? _selectedImageUrl;
bool _isLoadingImage = false;
/// Google Maps API key for location services
static final String _apiKey = dotenv.env['GOOGLE_MAPS_API_KEY'] ?? '';
/// Participant management
final List<String> _participants = [];
/// Location autocomplete functionality
List<PlaceSuggestion> _placeSuggestions = [];
bool _isLoadingSuggestions = false;
OverlayEntry? _suggestionsOverlay;
final LayerLink _layerLink = LayerLink();
/// Determines if the widget is in editing mode
bool get isEditing => widget.tripToEdit != null;
@override
void initState() {
super.initState();
_initializeFormWithTrip();
_locationController.addListener(_onLocationChanged);
}
Future<void> _initializeFormWithTrip() async {
if (widget.tripToEdit != null) {
final trip = widget.tripToEdit!;
setState(() {
_titleController.text = trip.title;
_descriptionController.text = trip.description;
_locationController.text = trip.location;
_budgetController.text = trip.budget?.toString() ?? '';
_startDate = trip.startDate;
_endDate = trip.endDate;
_selectedImageUrl = trip.imageUrl; // Charger l'image existante
});
await _loadParticipantEmails(trip.participants);
}
}
void _onLocationChanged() {
final query = _locationController.text.trim();
if (query.length < 2) {
_hideSuggestions();
return;
}
_fetchPlaceSuggestions(query);
}
Future<void> _fetchPlaceSuggestions(String query) async {
if (_apiKey.isEmpty) {
return;
}
setState(() {
_isLoadingSuggestions = true;
});
try {
final url = Uri.parse(
'https://maps.googleapis.com/maps/api/place/autocomplete/json'
'?input=${Uri.encodeComponent(query)}'
'&types=(cities)'
'&language=fr'
'&key=$_apiKey'
);
final response = await http.get(url);
if (response.statusCode == 200) {
final data = json.decode(response.body);
if (data['status'] == 'OK') {
final predictions = data['predictions'] as List;
setState(() {
_placeSuggestions = predictions.map((prediction) {
return PlaceSuggestion(
placeId: prediction['place_id'],
description: prediction['description'],
);
}).toList();
_isLoadingSuggestions = false;
});
if (_placeSuggestions.isNotEmpty) {
_showSuggestions();
} else {
_hideSuggestions();
}
} else {
setState(() {
_placeSuggestions = [];
_isLoadingSuggestions = false;
});
_hideSuggestions();
}
} else {
setState(() {
_placeSuggestions = [];
_isLoadingSuggestions = false;
});
_hideSuggestions();
}
} catch (e) {
setState(() {
_placeSuggestions = [];
_isLoadingSuggestions = false;
});
_hideSuggestions();
}
}
// Nouvelle méthode pour afficher les suggestions
void _showSuggestions() {
_hideSuggestions(); // Masquer d'abord les suggestions existantes
if (_placeSuggestions.isEmpty) return;
_suggestionsOverlay = OverlayEntry(
builder: (context) => Positioned(
width: MediaQuery.of(context).size.width - 32, // Largeur du champ avec padding
child: CompositedTransformFollower(
link: _layerLink,
showWhenUnlinked: false,
offset: const Offset(0, 60), // Position sous le champ
child: Material(
elevation: 4,
borderRadius: BorderRadius.circular(8),
child: Container(
constraints: const BoxConstraints(maxHeight: 200),
decoration: BoxDecoration(
color: Theme.of(context).scaffoldBackgroundColor,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.grey[300]!),
),
child: ListView.builder(
shrinkWrap: true,
itemCount: _placeSuggestions.length,
itemBuilder: (context, index) {
final suggestion = _placeSuggestions[index];
return ListTile(
leading: const Icon(Icons.location_on, color: Colors.grey),
title: Text(
suggestion.description,
style: const TextStyle(fontSize: 14),
),
dense: true,
onTap: () => _selectSuggestion(suggestion),
);
},
),
),
),
),
),
);
Overlay.of(context).insert(_suggestionsOverlay!);
}
void _hideSuggestions() {
_suggestionsOverlay?.remove();
_suggestionsOverlay = null;
}
void _selectSuggestion(PlaceSuggestion suggestion) {
_locationController.text = suggestion.description;
_hideSuggestions();
setState(() {
_placeSuggestions = [];
});
// Charger l'image du lieu sélectionné
_loadPlaceImage(suggestion.description);
}
/// Charge l'image du lieu depuis Google Places API
Future<void> _loadPlaceImage(String location) async {
print('CreateTripContent: Chargement de l\'image pour: $location');
setState(() {
_isLoadingImage = true;
});
try {
final imageUrl = await _placeImageService.getPlaceImageUrl(location);
print('CreateTripContent: Image URL reçue: $imageUrl');
if (mounted) {
setState(() {
_selectedImageUrl = imageUrl;
_isLoadingImage = false;
});
print('CreateTripContent: État mis à jour avec imageUrl: $_selectedImageUrl');
}
} catch (e) {
print('CreateTripContent: Erreur lors du chargement de l\'image: $e');
if (mounted) {
setState(() {
_isLoadingImage = false;
});
_errorService.logError(
'create_trip_content.dart',
'Erreur lors du chargement de l\'image: $e',
);
}
}
}
Future<void> _loadParticipantEmails(List<String> participantIds) async {
final userState = context.read<UserBloc>().state;
String? currentUserId;
if (userState is user_state.UserLoaded) {
currentUserId = userState.user.id;
}
for (String userId in participantIds) {
if (userId == currentUserId) continue;
try {
final userDoc = await _userService.getUserById(userId);
if (userDoc != null && userDoc.email.isNotEmpty) {
setState(() {
_participants.add(userDoc.email);
});
}
} catch (e) {
_errorService.logError(
'create_trip_content.dart',
'Erreur chargement participant $userId: $e',
);
}
}
}
@override
void dispose() {
_titleController.dispose();
_descriptionController.dispose();
_locationController.dispose();
_budgetController.dispose();
_participantController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocListener<TripBloc, TripState>(
listener: (context, tripState) {
if (tripState is TripCreated) {
// Stocker l'ID du trip et créer le groupe
_createdTripId = tripState.tripId;
_createGroupAndAccountForTrip(_createdTripId!);
} else if (tripState is TripOperationSuccess) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(tripState.message),
backgroundColor: Colors.green,
),
);
setState(() {
_isLoading = false;
});
Navigator.pop(context);
if (isEditing) {
Navigator.pop(context);
}
}
} else if (tripState is TripError) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(tripState.message),
backgroundColor: Colors.red,
),
);
setState(() {
_isLoading = false;
});
}
}
},
child: BlocBuilder<UserBloc, user_state.UserState>(
builder: (context, userState) {
if (userState is! user_state.UserLoaded) {
return Scaffold(
appBar: AppBar(
title: Text(isEditing ? 'Modifier le voyage' : 'Créer un voyage'),
),
body: Center(child: Text('Veuillez vous connecter')),
);
}
return Scaffold(
appBar: AppBar(
title: Text(isEditing ? 'Modifier le voyage' : 'Créer un voyage'),
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Colors.white,
),
body: GestureDetector(
onTap: _hideSuggestions, // Masquer les suggestions en tapant ailleurs
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildSectionTitle('Informations générales'),
const SizedBox(height: 16),
TextFormField(
controller: _titleController,
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Titre requis';
}
return null;
},
decoration: InputDecoration(
labelText: 'Titre du voyage *',
hintText: 'ex: Voyage à Paris',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: const Icon(Icons.travel_explore),
),
),
const SizedBox(height: 16),
TextFormField(
controller: _descriptionController,
maxLines: 3,
decoration: InputDecoration(
labelText: 'Description',
hintText: 'Décrivez votre voyage...',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: const Icon(Icons.description),
),
),
const SizedBox(height: 16),
// Champ de localisation avec suggestions
CompositedTransformTarget(
link: _layerLink,
child: TextFormField(
controller: _locationController,
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Destination requise';
}
return null;
},
decoration: InputDecoration(
labelText: 'Destination *',
hintText: 'ex: Paris, France',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: const Icon(Icons.location_on),
suffixIcon: _isLoadingSuggestions
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: null,
),
),
),
const SizedBox(height: 16),
// Aperçu de l'image du lieu
if (_isLoadingImage || _selectedImageUrl != null) ...[
_buildSectionTitle('Aperçu de la destination'),
const SizedBox(height: 8),
Container(
width: double.infinity,
height: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.grey[300]!),
),
child: _isLoadingImage
? const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
SizedBox(height: 8),
Text('Chargement de l\'image...'),
],
),
)
: _selectedImageUrl != null
? ClipRRect(
borderRadius: BorderRadius.circular(12),
child: Image.network(
_selectedImageUrl!,
width: double.infinity,
height: 200,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return Container(
width: double.infinity,
height: 200,
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(12),
),
child: const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.error, color: Colors.grey),
Text('Erreur de chargement'),
],
),
),
);
},
),
)
: const SizedBox(),
),
const SizedBox(height: 16),
],
const SizedBox(height: 24),
_buildSectionTitle('Dates du voyage'),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: _buildDateField(
label: 'Date de début *',
date: _startDate,
onTap: () => _selectStartDate(context),
),
),
const SizedBox(width: 16),
Expanded(
child: _buildDateField(
label: 'Date de fin *',
date: _endDate,
onTap: () => _selectEndDate(context),
),
),
],
),
const SizedBox(height: 24),
_buildSectionTitle('Budget'),
const SizedBox(height: 16),
TextFormField(
controller: _budgetController,
keyboardType: TextInputType.numberWithOptions(decimal: true),
decoration: InputDecoration(
labelText: 'Budget estimé',
hintText: 'ex: 1200.50',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: const Icon(Icons.euro),
suffixText: '',
),
),
const SizedBox(height: 24),
_buildSectionTitle('Participants'),
const SizedBox(height: 8),
Text(
'Ajoutez les emails des personnes que vous souhaitez inviter',
style: TextStyle(color: Colors.grey[600], fontSize: 14),
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: TextFormField(
controller: _participantController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email du participant',
hintText: 'ex: ami@email.com',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: const Icon(Icons.person_add),
),
),
),
const SizedBox(width: 8),
ElevatedButton(
onPressed: _addParticipant,
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
padding: const EdgeInsets.all(16),
),
child: const Icon(Icons.add),
),
],
),
const SizedBox(height: 16),
if (_participants.isNotEmpty) ...[
Text(
'Participants ajoutés (${_participants.length})',
style: const TextStyle(fontWeight: FontWeight.w500),
),
const SizedBox(height: 8),
Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300]!),
borderRadius: BorderRadius.circular(12),
),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: _participants
.map(
(email) => Chip(
label: Text(email, style: const TextStyle(fontSize: 12)),
deleteIcon: const Icon(Icons.close, size: 18),
onDeleted: () => _removeParticipant(email),
backgroundColor: Theme.of(context)
.colorScheme
.primary
.withValues(alpha: 0.1),
),
)
.toList(),
),
),
],
const SizedBox(height: 32),
SizedBox(
width: double.infinity,
height: 50,
child: ElevatedButton(
onPressed: _isLoading ? null : () => _saveTrip(userState.user),
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
child: _isLoading
? const CircularProgressIndicator(color: Colors.white)
: Text(
isEditing ? 'Mettre à jour le voyage' : 'Créer le voyage',
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
const SizedBox(height: 20),
],
),
),
),
),
);
},
),
);
}
Widget _buildSectionTitle(String title) {
return Text(
title,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.grey[700],
),
);
}
Widget _buildDateField({
required String label,
required DateTime? date,
required VoidCallback onTap,
}) {
final isDarkMode = Theme.of(context).brightness == Brightness.dark;
final textColor = isDarkMode ? Colors.white : Colors.black;
final labelColor = isDarkMode ? Colors.white70 : Colors.grey[600];
final iconColor = isDarkMode ? Colors.white70 : Colors.grey[600];
final placeholderColor = isDarkMode ? Colors.white38 : Colors.grey[500];
return InkWell(
onTap: onTap,
child: Container(
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
border: Border.all(color: isDarkMode ? Colors.white24 : Colors.grey[400]!),
borderRadius: BorderRadius.circular(12),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: TextStyle(fontSize: 12, color: labelColor)),
SizedBox(height: 8),
Row(
children: [
Icon(Icons.calendar_today, size: 16, color: iconColor),
SizedBox(width: 8),
Text(
date != null ? '${date.day}/${date.month}/${date.year}' : 'Sélectionner',
style: TextStyle(
fontSize: 16,
color: date != null ? textColor : placeholderColor,
),
),
],
),
],
),
),
);
}
Future<void> _selectStartDate(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: _startDate ?? DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime.now().add(Duration(days: 365 * 2)),
);
if (picked != null) {
setState(() {
_startDate = picked;
if (_endDate != null && _endDate!.isBefore(picked)) {
_endDate = null;
}
});
}
}
Future<void> _selectEndDate(BuildContext context) async {
if (_startDate == null) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Veuillez d\'abord sélectionner la date de début')),
);
}
return;
}
final DateTime? picked = await showDatePicker(
context: context,
initialDate: _endDate ?? _startDate!.add(Duration(days: 1)),
firstDate: _startDate!,
lastDate: DateTime.now().add(Duration(days: 365 * 2)),
);
if (picked != null && mounted) {
setState(() {
_endDate = picked;
});
}
}
void _addParticipant() {
final email = _participantController.text.trim();
if (email.isEmpty) return;
final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
if (!emailRegex.hasMatch(email)) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Email invalide')));
}
return;
}
if (_participants.contains(email)) {
if (mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Ce participant est déjà ajouté')));
}
return;
}
setState(() {
_participants.add(email);
_participantController.clear();
});
}
void _removeParticipant(String email) {
setState(() {
_participants.remove(email);
});
}
// Mettre à jour le groupe avec les nouveaux membres
Future<void> _updateGroupMembers(
String tripId,
user_state.UserModel currentUser,
List<Map<String, String>> participantsData,
) async {
final groupBloc = context.read<GroupBloc>();
try {
final group = await _groupRepository.getGroupByTripId(tripId);
if (group == null) {
_errorService.logError(
'create_trip_content.dart',
'Groupe non trouvé pour le voyage $tripId',
);
return;
}
final newMembers = await _createMembers();
final currentMembers = await _groupRepository.getGroupMembers(group.id);
final currentMemberIds = currentMembers.map((m) => m.userId).toSet();
final newMemberIds = newMembers.map((m) => m.userId).toSet();
final membersToAdd = newMembers.where((m) => !currentMemberIds.contains(m.userId)).toList();
final membersToRemove = currentMembers
.where((m) => !newMemberIds.contains(m.userId) && m.role != 'admin')
.toList();
for (final member in membersToAdd) {
if (mounted) {
groupBloc.add(AddMemberToGroup(group.id, member));
}
}
for (final member in membersToRemove) {
if (mounted) {
groupBloc.add(RemoveMemberFromGroup(group.id, member.userId));
}
}
} catch (e) {
_errorService.logError(
'create_trip_content.dart',
'Erreur lors de la mise à jour du groupe: $e',
);
}
}
Future<List<GroupMember>> _createMembers() async {
final userState = context.read<UserBloc>().state;
if (userState is! user_state.UserLoaded) return [];
final currentUser = userState.user;
final participantsData = await _getParticipantsData(_participants);
final groupMembers = <GroupMember>[
GroupMember(
userId: currentUser.id,
firstName: currentUser.prenom,
pseudo: currentUser.prenom,
role: 'admin',
),
...participantsData.map((p) => GroupMember(
userId: p['id'] as String,
firstName: p['firstName'] as String,
pseudo: p['firstName'] as String,
role: 'member',
)),
];
return groupMembers;
}
Future<void> _createGroupAndAccountForTrip(String tripId) async {
final groupBloc = context.read<GroupBloc>();
final accountBloc = context.read<AccountBloc>();
try {
final userState = context.read<UserBloc>().state;
if (userState is! user_state.UserLoaded) {
throw Exception('Utilisateur non connecté');
}
final currentUser = userState.user;
final group = Group(
id: '',
name: _titleController.text.trim(),
tripId: tripId,
createdBy: currentUser.id,
);
final groupMembers = await _createMembers();
if (groupMembers.isEmpty) {
throw Exception('Erreur lors de la création des membres du groupe');
}
groupBloc.add(CreateGroupWithMembers(
group: group,
members: groupMembers,
));
final account = Account(
id: '',
tripId: tripId,
name: _titleController.text.trim(),
);
accountBloc.add(CreateAccountWithMembers(
account: account,
members: groupMembers,
));
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Voyage, groupe et compte créés avec succès !'),
backgroundColor: Colors.green,
),
);
setState(() {
_isLoading = false;
});
Navigator.pop(context);
}
} catch (e) {
_errorService.logError(
'create_trip_content.dart',
'Erreur lors de la création du groupe et compte: $e',
);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Erreur: $e'),
backgroundColor: Colors.red,
),
);
setState(() {
_isLoading = false;
});
}
}
}
Future<void> _saveTrip(user_state.UserModel currentUser) async {
if (!_formKey.currentState!.validate()) {
return;
}
if (_startDate == null || _endDate == null) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Veuillez sélectionner les dates')),
);
}
return;
}
setState(() {
_isLoading = true;
});
final tripBloc = context.read<TripBloc>();
try {
final participantsData = await _getParticipantsData(_participants);
List<String> participantIds = participantsData.map((p) => p['id'] as String).toList();
if (!participantIds.contains(currentUser.id)) {
participantIds.insert(0, currentUser.id);
}
final trip = Trip(
id: isEditing ? widget.tripToEdit!.id : '',
title: _titleController.text.trim(),
description: _descriptionController.text.trim(),
location: _locationController.text.trim(),
startDate: _startDate!,
endDate: _endDate!,
budget: double.tryParse(_budgetController.text) ?? 0.0,
createdBy: currentUser.id,
participants: participantIds,
createdAt: isEditing ? widget.tripToEdit!.createdAt : DateTime.now(),
updatedAt: DateTime.now(),
imageUrl: _selectedImageUrl, // Ajouter l'URL de l'image
);
if (isEditing) {
// Mode mise à jour
tripBloc.add(TripUpdateRequested(trip: trip));
await _updateGroupMembers(
widget.tripToEdit!.id!,
currentUser,
participantsData,
);
} else {
// Mode création - Le groupe sera créé dans le listener TripCreated
tripBloc.add(TripCreateRequested(trip: trip));
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Erreur: $e'),
backgroundColor: Colors.red,
),
);
setState(() {
_isLoading = false;
});
}
}
}
Future<List<Map<String, String>>> _getParticipantsData(List<String> emails) async {
List<Map<String, String>> participantsData = [];
for (String email in emails) {
try {
final userId = await _userService.getUserIdByEmail(email);
if (userId != null) {
final userDoc = await _userService.getUserById(userId);
final firstName = userDoc?.prenom ?? 'Utilisateur';
participantsData.add({
'id': userId,
'firstName': firstName,
});
} else {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Utilisateur non trouvé: $email'),
backgroundColor: Colors.orange,
),
);
}
}
} catch (e) {
_errorService.logError(
'create_trip_content.dart',
'Erreur lors de la récupération de l\'utilisateur $email: $e',
);
}
}
return participantsData;
}
}
class PlaceSuggestion {
final String placeId;
final String description;
PlaceSuggestion({
required this.placeId,
required this.description,
});
}