feat: Enhance trip creation and management features with user validation, improved error handling, and Firestore integration

This commit is contained in:
Dayron
2025-10-07 11:38:20 +02:00
parent c90011ef5d
commit 4e403f3308
5 changed files with 625 additions and 225 deletions

View File

@@ -1,4 +1,8 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:travel_mate/models/trip.dart';
import 'package:travel_mate/providers/user_provider.dart';
import 'package:travel_mate/services/trip_service.dart';
class CreateTripContent extends StatefulWidget {
@@ -428,10 +432,70 @@ class _CreateTripContentState extends State<CreateTripContent> {
});
try {
// TODO: Implémenter la sauvegarde du voyage
await Future.delayed(Duration(seconds: 2)); // Simulation
final userProvider = Provider.of<UserProvider>(context, listen: false);
final currentUser = userProvider.currentUser;
if (mounted) {
if (currentUser == null) {
throw Exception('Utilisateur non connecté');
}
print('Création du voyage par: ${currentUser.id} (${currentUser.email})');
// Convertir les emails en IDs utilisateur
List<String> participantIds = [];
// Ajouter automatiquement le créateur
if (currentUser.id != null) {
participantIds.add(currentUser.id!);
}
// Convertir chaque email en ID utilisateur
for (String email in _participants) {
try {
final userId = await userProvider.getUserIdByEmail(email);
if (userId != null && !participantIds.contains(userId)) {
participantIds.add(userId);
print('Email $email converti en ID: $userId');
} else if (userId == null) {
print('Utilisateur non trouvé pour l\'email: $email');
// Optionnel: afficher un warning à l'utilisateur
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Utilisateur non trouvé pour l\'email: $email'),
backgroundColor: Colors.orange,
duration: Duration(seconds: 2),
),
);
}
} catch (e) {
print('Erreur lors de la recherche de l\'utilisateur $email: $e');
}
}
// Créer l'objet Trip avec les IDs des participants
final trip = Trip(
id: '', // Sera généré par Firebase
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, // Contient uniquement les IDs
createdAt: DateTime.now(),
updatedAt: DateTime.now(),
);
print('Participants IDs: $participantIds');
print('Données du voyage: ${trip.toMap()}');
// Sauvegarder le voyage
final tripService = TripService();
final success = await tripService.addTrip(trip);
if (success && mounted) {
print('Voyage créé avec succès !');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Voyage créé avec succès !'),
@@ -439,9 +503,12 @@ class _CreateTripContentState extends State<CreateTripContent> {
),
);
Navigator.pop(context);
Navigator.pop(context, true); // Retourner true pour indiquer le succès
} else {
throw Exception('Erreur lors de la sauvegarde');
}
} catch (e) {
print('Erreur lors de la création: $e');
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(

View File

@@ -2,10 +2,19 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:travel_mate/components/home/create_trip_content.dart';
import '../../providers/user_provider.dart';
import '../../services/trip_service.dart';
import '../../models/trip.dart';
class HomeContent extends StatelessWidget {
class HomeContent extends StatefulWidget {
const HomeContent({super.key});
@override
State<HomeContent> createState() => _HomeContentState();
}
class _HomeContentState extends State<HomeContent> {
final TripService _tripService = TripService();
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -13,72 +22,102 @@ class HomeContent extends StatelessWidget {
builder: (context, userProvider, child) {
final user = userProvider.currentUser;
return SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Header de bienvenue
Text(
'Bonjour ${user?.prenom ?? 'Voyageur'} !',
style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
),
SizedBox(height: 8),
Text(
'Vos voyages en cours',
style: TextStyle(fontSize: 16, color: Colors.grey[600]),
),
SizedBox(height: 20),
if (user == null || user.id == null) {
return Center(
child: Text('Utilisateur non connecté'),
);
}
// Liste des groupes/voyages
_buildTravelCard(
context,
title: 'Voyage à Paris',
location: 'Paris, France',
dates: '15-20 Juin 2024',
participants: ['Alice', 'Bob', 'Charlie'],
budget: 1200.50,
imageUrl:
'https://images.unsplash.com/photo-1502602898536-47ad22581b52',
color: Colors.blue,
),
return StreamBuilder<List<Trip>>(
stream: _tripService.getTripsStreamByUser(user.id!, user.email),
builder: (context, snapshot) {
print('StreamBuilder - ConnectionState: ${snapshot.connectionState}');
print('StreamBuilder - HasError: ${snapshot.hasError}');
print('StreamBuilder - Data: ${snapshot.data?.length ?? 0} trips');
if (snapshot.connectionState == ConnectionState.waiting) {
return _buildLoadingState();
}
_buildTravelCard(
context,
title: 'Road Trip Espagne',
location: 'Madrid, Espagne',
dates: '10-18 Août 2024',
participants: ['Marie', 'Paul', 'Sophie', 'Thomas'],
budget: 850.75,
imageUrl:
'https://images.unsplash.com/photo-1539037116277-4db20889f2d4',
color: Colors.orange,
),
if (snapshot.hasError) {
print('Erreur du stream: ${snapshot.error}');
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.error, size: 64, color: Colors.red),
SizedBox(height: 16),
Text('Erreur lors du chargement des voyages'),
SizedBox(height: 8),
Text('${snapshot.error}'),
SizedBox(height: 8),
ElevatedButton(
onPressed: () {
setState(() {}); // Forcer le rebuild
},
child: Text('Réessayer'),
),
],
),
);
}
_buildTravelCard(
context,
title: 'Weekend à Amsterdam',
location: 'Amsterdam, Pays-Bas',
dates: '3-5 Septembre 2024',
participants: ['Emma', 'Lucas'],
budget: 450.25,
imageUrl:
'https://images.unsplash.com/photo-1534351450181-ea9f78427fe8',
color: Colors.green,
),
final trips = snapshot.data ?? [];
print('Trips reçus du stream: ${trips.length}');
// Espacement en bas pour éviter que le FAB cache le contenu
const SizedBox(height: 80),
],
),
return RefreshIndicator(
onRefresh: () async {
setState(() {}); // Forcer le rebuild du stream
},
child: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Header de bienvenue
Text(
'Bonjour ${user.prenom ?? 'Voyageur'} !',
style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
),
SizedBox(height: 8),
Text(
'Vos voyages',
style: TextStyle(fontSize: 16, color: Colors.grey[600]),
),
SizedBox(height: 20),
// Contenu principal
trips.isEmpty ? _buildEmptyState() : _buildTripsList(trips),
// Espacement en bas pour éviter que le FAB cache le contenu
const SizedBox(height: 80),
],
),
),
);
},
);
},
),
// FloatingActionButton intégré directement dans HomeContent
// FloatingActionButton
floatingActionButton: FloatingActionButton(
onPressed: () {
_showCreateTravelDialog(context);
onPressed: () async {
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => CreateTripContent()),
);
// Le stream se mettra à jour automatiquement
if (result == true) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Voyage créé ! Il apparaîtra dans quelques secondes.'),
backgroundColor: Colors.green,
),
);
}
},
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Colors.white,
@@ -88,24 +127,67 @@ class HomeContent extends StatelessWidget {
);
}
Widget _buildTravelCard(
BuildContext context, {
required String title,
required String location,
required String dates,
required List<String> participants,
required double budget,
required String imageUrl,
required Color color,
}) {
Widget _buildLoadingState() {
return Center(
child: Padding(
padding: EdgeInsets.all(32),
child: CircularProgressIndicator(),
),
);
}
Widget _buildEmptyState() {
return Center(
child: Padding(
padding: EdgeInsets.all(32),
child: Column(
children: [
Icon(
Icons.travel_explore,
size: 64,
color: Colors.grey[400],
),
SizedBox(height: 16),
Text(
'Aucun voyage pour le moment',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
color: Colors.grey[600],
),
),
SizedBox(height: 8),
Text(
'Créez votre premier voyage en appuyant sur le bouton +',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14,
color: Colors.grey[500],
),
),
],
),
),
);
}
Widget _buildTripsList(List<Trip> trips) {
return Column(
children: trips.map((trip) => _buildTravelCard(trip)).toList(),
);
}
Widget _buildTravelCard(Trip trip) {
final colors = [Colors.blue, Colors.orange, Colors.green, Colors.purple, Colors.red];
final color = colors[trip.title.hashCode.abs() % colors.length];
return Card(
elevation: 4,
margin: const EdgeInsets.only(bottom: 16),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: InkWell(
onTap: () {
// Navigation vers les détails du voyage
_showTravelDetails(context, title);
_showTravelDetails(context, trip);
},
borderRadius: BorderRadius.circular(12),
child: Column(
@@ -127,7 +209,6 @@ class HomeContent extends StatelessWidget {
),
child: Stack(
children: [
// Image placeholder (vous pouvez utiliser Network.image avec imageUrl)
Container(
width: double.infinity,
decoration: BoxDecoration(
@@ -137,8 +218,6 @@ class HomeContent extends StatelessWidget {
color: color.withValues(alpha: 0.3),
),
),
// Titre et localisation
Positioned(
bottom: 16,
left: 16,
@@ -147,7 +226,7 @@ class HomeContent extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
trip.title,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
@@ -163,11 +242,14 @@ class HomeContent extends StatelessWidget {
size: 16,
),
const SizedBox(width: 4),
Text(
location,
style: const TextStyle(
fontSize: 14,
color: Colors.white,
Expanded(
child: Text(
trip.location,
style: const TextStyle(
fontSize: 14,
color: Colors.white,
),
overflow: TextOverflow.ellipsis,
),
),
],
@@ -185,6 +267,20 @@ class HomeContent extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Description
if (trip.description.isNotEmpty) ...[
Text(
trip.description,
style: TextStyle(
fontSize: 14,
color: Colors.grey[700],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
SizedBox(height: 12),
],
// Dates
Row(
children: [
@@ -195,7 +291,7 @@ class HomeContent extends StatelessWidget {
),
SizedBox(width: 8),
Text(
dates,
'${trip.startDate.day}/${trip.startDate.month}/${trip.startDate.year} - ${trip.endDate.day}/${trip.endDate.month}/${trip.endDate.year}',
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
@@ -209,53 +305,15 @@ class HomeContent extends StatelessWidget {
// Participants
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.group, size: 16, color: Colors.grey[600]),
SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${participants.length} participant${participants.length > 1 ? 's' : ''}',
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
fontWeight: FontWeight.w500,
),
),
SizedBox(height: 4),
Wrap(
spacing: 4,
children: participants
.take(3)
.map(
(name) => Chip(
label: Text(
name,
style: TextStyle(fontSize: 12),
),
backgroundColor: color.withValues(
alpha: 0.1,
),
materialTapTargetSize:
MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.compact,
),
)
.toList(),
),
if (participants.length > 3)
Text(
'+${participants.length - 3} autres',
style: TextStyle(
fontSize: 12,
color: Colors.grey[500],
fontStyle: FontStyle.italic,
),
),
],
Text(
'${trip.participants.length} participant${trip.participants.length > 0 ? 's' : ''}',
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
fontWeight: FontWeight.w500,
),
),
],
@@ -263,40 +321,40 @@ class HomeContent extends StatelessWidget {
SizedBox(height: 12),
// Budget
// Budget et statut
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Icon(Icons.euro, size: 16, color: Colors.grey[600]),
SizedBox(width: 8),
Text(
'Budget: ${budget.toStringAsFixed(2)}',
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
fontWeight: FontWeight.w500,
if (trip.budget! > 0)
Row(
children: [
Icon(Icons.euro, size: 16, color: Colors.grey[600]),
SizedBox(width: 8),
Text(
'Budget: ${trip.budget?.toStringAsFixed(2)}',
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
fontWeight: FontWeight.w500,
),
),
),
],
),
],
),
// Statut
Container(
padding: EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
decoration: BoxDecoration(
color: Colors.green.withValues(alpha: 0.1),
color: _getStatusColor(trip).withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12),
),
child: Text(
'En cours',
_getStatusText(trip),
style: TextStyle(
fontSize: 12,
color: Colors.green[700],
color: _getStatusColor(trip),
fontWeight: FontWeight.w500,
),
),
@@ -312,24 +370,55 @@ class HomeContent extends StatelessWidget {
);
}
void _showTravelDetails(BuildContext context, String title) {
Color _getStatusColor(Trip trip) {
final now = DateTime.now();
if (trip.endDate.isBefore(now)) {
return Colors.grey;
} else if (trip.startDate.isBefore(now) && trip.endDate.isAfter(now)) {
return Colors.green;
} else {
return Colors.blue;
}
}
String _getStatusText(Trip trip) {
final now = DateTime.now();
if (trip.endDate.isBefore(now)) {
return 'Terminé';
} else if (trip.startDate.isBefore(now) && trip.endDate.isAfter(now)) {
return 'En cours';
} else {
return 'À venir';
}
}
void _showTravelDetails(BuildContext context, Trip trip) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(
child: Text('Détails du voyage: $title\n(À implémenter)'),
appBar: AppBar(title: Text(trip.title)),
body: Padding(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Destination: ${trip.location}'),
SizedBox(height: 8),
Text('Description: ${trip.description}'),
SizedBox(height: 8),
Text('Dates: ${trip.startDate.day}/${trip.startDate.month}/${trip.startDate.year} - ${trip.endDate.day}/${trip.endDate.month}/${trip.endDate.year}'),
SizedBox(height: 8),
Text('Budget: ${trip.budget}'),
SizedBox(height: 8),
Text('Participants: ${trip.participants.length}'),
SizedBox(height: 16),
Text('(Détails complets à implémenter)'),
],
),
),
),
),
);
}
void _showCreateTravelDialog(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CreateTripContent()),
);
}
}