feat: Integrate ErrorService for improved error handling and add imageUrl field to Trip model

This commit is contained in:
Van Leemput Dayron
2025-11-03 11:33:25 +01:00
parent 882f7c8963
commit 83aed85fea
3 changed files with 223 additions and 174 deletions

View File

@@ -10,7 +10,7 @@ import '../../blocs/trip/trip_event.dart';
import '../../models/trip.dart'; import '../../models/trip.dart';
/// Home content widget for the main application dashboard. /// Home content widget for the main application dashboard.
/// ///
/// This widget serves as the primary content area of the home screen, /// This widget serves as the primary content area of the home screen,
/// displaying user trips and providing navigation to trip management /// displaying user trips and providing navigation to trip management
/// features. Key functionality includes: /// features. Key functionality includes:
@@ -18,7 +18,7 @@ import '../../models/trip.dart';
/// - Creating new trips /// - Creating new trips
/// - Viewing trip details /// - Viewing trip details
/// - Managing trip state with proper user authentication /// - Managing trip state with proper user authentication
/// ///
/// The widget maintains state persistence using AutomaticKeepAliveClientMixin /// The widget maintains state persistence using AutomaticKeepAliveClientMixin
/// to preserve content when switching between tabs. /// to preserve content when switching between tabs.
class HomeContent extends StatefulWidget { class HomeContent extends StatefulWidget {
@@ -29,11 +29,12 @@ class HomeContent extends StatefulWidget {
State<HomeContent> createState() => _HomeContentState(); State<HomeContent> createState() => _HomeContentState();
} }
class _HomeContentState extends State<HomeContent> with AutomaticKeepAliveClientMixin { class _HomeContentState extends State<HomeContent>
with AutomaticKeepAliveClientMixin {
/// Preserves widget state when switching between tabs /// Preserves widget state when switching between tabs
@override @override
bool get wantKeepAlive => true; bool get wantKeepAlive => true;
/// Flag to prevent duplicate trip loading operations /// Flag to prevent duplicate trip loading operations
bool _hasLoadedTrips = false; bool _hasLoadedTrips = false;
@@ -47,7 +48,7 @@ class _HomeContentState extends State<HomeContent> with AutomaticKeepAliveClient
} }
/// Loads trips if a user is currently loaded and trips haven't been loaded yet. /// Loads trips if a user is currently loaded and trips haven't been loaded yet.
/// ///
/// Checks the current user state and initiates trip loading if the user is /// Checks the current user state and initiates trip loading if the user is
/// authenticated and trips haven't been loaded previously. This prevents /// authenticated and trips haven't been loaded previously. This prevents
/// duplicate loading operations. /// duplicate loading operations.
@@ -56,7 +57,9 @@ class _HomeContentState extends State<HomeContent> with AutomaticKeepAliveClient
final userState = context.read<UserBloc>().state; final userState = context.read<UserBloc>().state;
if (userState is UserLoaded) { if (userState is UserLoaded) {
_hasLoadedTrips = true; _hasLoadedTrips = true;
context.read<TripBloc>().add(LoadTripsByUserId(userId: userState.user.id)); context.read<TripBloc>().add(
LoadTripsByUserId(userId: userState.user.id),
);
} }
} }
} }
@@ -64,15 +67,11 @@ class _HomeContentState extends State<HomeContent> with AutomaticKeepAliveClient
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
super.build(context); // Important pour AutomaticKeepAliveClientMixin super.build(context); // Important pour AutomaticKeepAliveClientMixin
return BlocBuilder<UserBloc, UserState>( return BlocBuilder<UserBloc, UserState>(
builder: (context, userState) { builder: (context, userState) {
if (userState is UserLoading) { if (userState is UserLoading) {
return Scaffold( return Scaffold(body: Center(child: CircularProgressIndicator()));
body: Center(
child: CircularProgressIndicator(),
),
);
} }
if (userState is UserError) { if (userState is UserError) {
@@ -91,11 +90,7 @@ class _HomeContentState extends State<HomeContent> with AutomaticKeepAliveClient
} }
if (userState is! UserLoaded) { if (userState is! UserLoaded) {
return Scaffold( return Scaffold(body: Center(child: Text('Veuillez vous connecter')));
body: Center(
child: Text('Veuillez vous connecter'),
),
);
} }
final user = userState.user; final user = userState.user;
@@ -137,7 +132,9 @@ class _HomeContentState extends State<HomeContent> with AutomaticKeepAliveClient
return Scaffold( return Scaffold(
body: RefreshIndicator( body: RefreshIndicator(
onRefresh: () async { onRefresh: () async {
context.read<TripBloc>().add(LoadTripsByUserId(userId: user.id)); context.read<TripBloc>().add(
LoadTripsByUserId(userId: user.id),
);
await Future.delayed(Duration(milliseconds: 500)); await Future.delayed(Duration(milliseconds: 500));
}, },
child: SingleChildScrollView( child: SingleChildScrollView(
@@ -149,21 +146,21 @@ class _HomeContentState extends State<HomeContent> with AutomaticKeepAliveClient
Text( Text(
'Bonjour ${user.prenom} !', 'Bonjour ${user.prenom} !',
style: TextStyle( style: TextStyle(
fontSize: 28, fontSize: 28,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: Theme.of(context).brightness == Brightness.dark color: Theme.of(context).brightness == Brightness.dark
? Colors.white ? Colors.white
: Colors.black, : Colors.black,
), ),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Text( Text(
'Vos voyages', 'Vos voyages',
style: TextStyle( style: TextStyle(
fontSize: 16, fontSize: 16,
color: Theme.of(context).brightness == Brightness.dark color: Theme.of(context).brightness == Brightness.dark
? Colors.white70 ? Colors.white70
: Colors.grey[600], : Colors.grey[600],
), ),
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
@@ -192,7 +189,9 @@ class _HomeContentState extends State<HomeContent> with AutomaticKeepAliveClient
final result = await Navigator.push( final result = await Navigator.push(
context, context,
MaterialPageRoute(builder: (context) => const CreateTripContent()), MaterialPageRoute(
builder: (context) => const CreateTripContent(),
),
); );
if (result == true && mounted) { if (result == true && mounted) {
@@ -203,7 +202,8 @@ class _HomeContentState extends State<HomeContent> with AutomaticKeepAliveClient
foregroundColor: Colors.white, foregroundColor: Colors.white,
child: const Icon(Icons.add), child: const Icon(Icons.add),
), ),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat, floatingActionButtonLocation:
FloatingActionButtonLocation.endFloat,
); );
}, },
); );
@@ -274,9 +274,7 @@ class _HomeContentState extends State<HomeContent> with AutomaticKeepAliveClient
} }
Widget _buildTripsList(List<Trip> trips) { Widget _buildTripsList(List<Trip> trips) {
return Column( return Column(children: trips.map((trip) => _buildTripCard(trip)).toList());
children: trips.map((trip) => _buildTripCard(trip)).toList(),
);
} }
Widget _buildTripCard(Trip trip) { Widget _buildTripCard(Trip trip) {
@@ -287,141 +285,186 @@ class _HomeContentState extends State<HomeContent> with AutomaticKeepAliveClient
return Card( return Card(
margin: EdgeInsets.only(bottom: 12), margin: EdgeInsets.only(bottom: 12),
elevation: 2, elevation: 2,
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
borderRadius: BorderRadius.circular(12), child: Column(
), crossAxisAlignment: CrossAxisAlignment.start,
child: InkWell( children: [
onTap: () async { // Image en haut de la carte
final result = await Navigator.push( Container(
context, height: 200,
MaterialPageRoute( width: double.infinity,
builder: (context) => ShowTripDetailsContent(trip: trip), decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(12),
topRight: Radius.circular(12),
),
color: Colors.grey[300],
), ),
); child: ClipRRect(
borderRadius: BorderRadius.only(
if (result == true && mounted) { topLeft: Radius.circular(12),
final userState = context.read<UserBloc>().state; topRight: Radius.circular(12),
if (userState is UserLoaded) { ),
context.read<TripBloc>().add(LoadTripsByUserId(userId: userState.user.id)); child: trip.imageUrl != null && trip.imageUrl!.isNotEmpty
} ? Image.network(
} trip.imageUrl!,
}, fit: BoxFit.cover,
borderRadius: BorderRadius.circular(12), errorBuilder: (context, error, stackTrace) {
child: Padding( return Container(
padding: EdgeInsets.all(16), color: Colors.grey[300],
child: Column( child: Icon(
crossAxisAlignment: CrossAxisAlignment.start, Icons.image_not_supported,
children: [ size: 50,
Row( color: Colors.grey[600],
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
trip.title,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: textColor,
), ),
), );
SizedBox(height: 4), },
Row( )
children: [ : Container(
Icon(Icons.location_on, size: 16, color: subtextColor), color: Colors.grey[300],
SizedBox(width: 4), child: Icon(
Text( Icons.travel_explore,
trip.location, size: 50,
style: TextStyle(color: subtextColor), color: Colors.grey[600],
),
],
),
],
),
),
Container(
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: _getStatusColor(trip).withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(12),
),
child: Text(
_getStatusText(trip),
style: TextStyle(
color: _getStatusColor(trip),
fontWeight: FontWeight.bold,
fontSize: 12,
), ),
), ),
),
),
// Contenu de la carte
Padding(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Nom du voyage
Text(
trip.title,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: textColor,
), ),
], ),
),
SizedBox(height: 12),
Row(
children: [
Icon(Icons.calendar_today, size: 16, color: subtextColor),
SizedBox(width: 4),
Text(
'${_formatDate(trip.startDate)} - ${_formatDate(trip.endDate)}',
style: TextStyle(fontSize: 14, color: subtextColor),
),
],
),
if (trip.budget != null) ...[
SizedBox(height: 8), SizedBox(height: 8),
// Section dates, participants et bouton
Row( Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Icon(Icons.euro, size: 16, color: subtextColor), // Colonne gauche : dates et participants
SizedBox(width: 4), Expanded(
Text( child: Column(
'${trip.budget!.toStringAsFixed(2)}', crossAxisAlignment: CrossAxisAlignment.start,
style: TextStyle(fontSize: 14, color: subtextColor), children: [
// Dates
Row(
children: [
Icon(
Icons.calendar_today,
size: 16,
color: subtextColor,
),
SizedBox(width: 4),
Text(
'${_formatDate(trip.startDate)} - ${_formatDate(trip.endDate)}',
style: TextStyle(
fontSize: 14,
color: subtextColor,
),
),
],
),
SizedBox(height: 8),
// Nombre de participants
Row(
children: [
Icon(Icons.people, size: 16, color: subtextColor),
SizedBox(width: 4),
Text(
'${trip.participants.length} participant${trip.participants.length > 1 ? 's' : ''}',
style: TextStyle(
fontSize: 14,
color: subtextColor,
),
),
],
),
],
),
),
// Bouton "Voir" à droite
ElevatedButton(
onPressed: () async {
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
ShowTripDetailsContent(trip: trip),
),
);
if (result == true && mounted) {
final userState = context.read<UserBloc>().state;
if (userState is UserLoaded) {
context.read<TripBloc>().add(
LoadTripsByUserId(userId: userState.user.id),
);
}
}
},
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Theme.of(
context,
).colorScheme.onPrimary,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
padding: EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
),
child: Text('Voir', style: TextStyle(fontSize: 14)),
), ),
], ],
), ),
], ],
SizedBox(height: 8), ),
Row(
children: [
Icon(Icons.people, size: 16, color: subtextColor),
SizedBox(width: 4),
Text(
'${trip.participants.length} participant${trip.participants.length > 1 ? 's' : ''}',
style: TextStyle(fontSize: 14, color: subtextColor),
),
],
),
],
), ),
), ],
), ),
); );
} }
Color _getStatusColor(Trip trip) { // Color _getStatusColor(Trip trip) {
final now = DateTime.now(); // final now = DateTime.now();
if (now.isBefore(trip.startDate)) { // if (now.isBefore(trip.startDate)) {
return Colors.blue; // return Colors.blue;
} else if (now.isAfter(trip.endDate)) { // } else if (now.isAfter(trip.endDate)) {
return Colors.grey; // return Colors.grey;
} else { // } else {
return Colors.green; // return Colors.green;
} // }
} // }
String _getStatusText(Trip trip) { // String _getStatusText(Trip trip) {
final now = DateTime.now(); // final now = DateTime.now();
if (now.isBefore(trip.startDate)) { // if (now.isBefore(trip.startDate)) {
return 'À venir'; // return 'À venir';
} else if (now.isAfter(trip.endDate)) { // } else if (now.isAfter(trip.endDate)) {
return 'Terminé'; // return 'Terminé';
} else { // } else {
return 'En cours'; // return 'En cours';
} // }
} // }
String _formatDate(DateTime date) { String _formatDate(DateTime date) {
return '${date.day}/${date.month}/${date.year}'; return '${date.day.toString().padLeft(2, '0')}/${date.month.toString().padLeft(2, '0')}/${date.year}';
} }
} }

View File

@@ -4,6 +4,7 @@ import 'package:travel_mate/blocs/trip/trip_bloc.dart';
import 'package:travel_mate/blocs/trip/trip_event.dart'; import 'package:travel_mate/blocs/trip/trip_event.dart';
import 'package:travel_mate/components/home/create_trip_content.dart'; import 'package:travel_mate/components/home/create_trip_content.dart';
import 'package:travel_mate/models/trip.dart'; import 'package:travel_mate/models/trip.dart';
import 'package:travel_mate/services/error_service.dart';
import 'package:url_launcher/url_launcher.dart'; // Ajouter cet import import 'package:url_launcher/url_launcher.dart'; // Ajouter cet import
import 'package:travel_mate/components/map/map_content.dart'; // Ajouter cet import si la page carte existe import 'package:travel_mate/components/map/map_content.dart'; // Ajouter cet import si la page carte existe
@@ -16,6 +17,8 @@ class ShowTripDetailsContent extends StatefulWidget {
} }
class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> { class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
final ErrorService _errorService = ErrorService();
// Méthode pour ouvrir la carte interne // Méthode pour ouvrir la carte interne
void _openInternalMap() { void _openInternalMap() {
Navigator.push( Navigator.push(
@@ -45,13 +48,9 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
} else { } else {
// Si rien ne marche, afficher un message d'erreur // Si rien ne marche, afficher un message d'erreur
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( _errorService.showError(
const SnackBar( message:
content: Text( 'Impossible d\'ouvrir Google Maps, veuillez vérifier que l\'application est installée.',
'Impossible d\'ouvrir Google Maps. Vérifiez que l\'application est installée.',
),
backgroundColor: Colors.red,
),
); );
} }
} }

View File

@@ -2,49 +2,51 @@ import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:cloud_firestore/cloud_firestore.dart';
/// Model representing a travel trip in the application. /// Model representing a travel trip in the application.
/// ///
/// This class encapsulates all trip-related information including dates, /// This class encapsulates all trip-related information including dates,
/// location, participants, and budget details. It provides serialization /// location, participants, and budget details. It provides serialization
/// methods for Firebase operations and supports trip lifecycle management. /// methods for Firebase operations and supports trip lifecycle management.
class Trip { class Trip {
/// Unique identifier for the trip (usually Firestore document ID). /// Unique identifier for the trip (usually Firestore document ID).
final String? id; final String? id;
/// Title or name of the trip. /// Title or name of the trip.
final String title; final String title;
/// Detailed description of the trip. /// Detailed description of the trip.
final String description; final String description;
/// Trip destination or location. /// Trip destination or location.
final String location; final String location;
/// Trip start date and time. /// Trip start date and time.
final DateTime startDate; final DateTime startDate;
/// Trip end date and time. /// Trip end date and time.
final DateTime endDate; final DateTime endDate;
/// Optional budget for the trip in the local currency. /// Optional budget for the trip in the local currency.
final double? budget; final double? budget;
/// List of participant user IDs. /// List of participant user IDs.
final List<String> participants; final List<String> participants;
/// User ID of the trip creator. /// User ID of the trip creator.
final String createdBy; final String createdBy;
/// Timestamp when the trip was created. /// Timestamp when the trip was created.
final DateTime createdAt; final DateTime createdAt;
/// Timestamp when the trip was last updated. /// Timestamp when the trip was last updated.
final DateTime updatedAt; final DateTime updatedAt;
/// Current status of the trip (e.g., 'draft', 'active', 'completed'). /// Current status of the trip (e.g., 'draft', 'active', 'completed').
final String status; final String status;
final String? imageUrl;
/// Creates a new [Trip] instance. /// Creates a new [Trip] instance.
/// ///
/// Most fields are required except [id] and [budget]. /// Most fields are required except [id] and [budget].
/// [status] defaults to 'draft' for new trips. /// [status] defaults to 'draft' for new trips.
Trip({ Trip({
@@ -60,32 +62,33 @@ class Trip {
required this.createdAt, required this.createdAt,
required this.updatedAt, required this.updatedAt,
this.status = 'draft', this.status = 'draft',
this.imageUrl,
}); });
// NOUVELLE MÉTHODE HELPER pour convertir n'importe quel format de date // NOUVELLE MÉTHODE HELPER pour convertir n'importe quel format de date
static DateTime _parseDateTime(dynamic value) { static DateTime _parseDateTime(dynamic value) {
if (value == null) return DateTime.now(); if (value == null) return DateTime.now();
// Si c'est déjà un Timestamp Firebase // Si c'est déjà un Timestamp Firebase
if (value is Timestamp) { if (value is Timestamp) {
return value.toDate(); return value.toDate();
} }
// Si c'est un int (millisecondes depuis epoch) // Si c'est un int (millisecondes depuis epoch)
if (value is int) { if (value is int) {
return DateTime.fromMillisecondsSinceEpoch(value); return DateTime.fromMillisecondsSinceEpoch(value);
} }
// Si c'est un String (ISO 8601) // Si c'est un String (ISO 8601)
if (value is String) { if (value is String) {
return DateTime.parse(value); return DateTime.parse(value);
} }
// Si c'est déjà un DateTime // Si c'est déjà un DateTime
if (value is DateTime) { if (value is DateTime) {
return value; return value;
} }
// Par défaut // Par défaut
return DateTime.now(); return DateTime.now();
} }
@@ -106,6 +109,7 @@ class Trip {
createdAt: _parseDateTime(map['createdAt']), createdAt: _parseDateTime(map['createdAt']),
updatedAt: _parseDateTime(map['updatedAt']), updatedAt: _parseDateTime(map['updatedAt']),
status: map['status'] as String? ?? 'draft', status: map['status'] as String? ?? 'draft',
imageUrl: map['imageUrl'] as String?,
); );
} catch (e) { } catch (e) {
rethrow; rethrow;
@@ -126,6 +130,7 @@ class Trip {
'createdAt': Timestamp.fromDate(createdAt), 'createdAt': Timestamp.fromDate(createdAt),
'updatedAt': Timestamp.fromDate(updatedAt), 'updatedAt': Timestamp.fromDate(updatedAt),
'status': status, 'status': status,
'imageUrl': imageUrl,
}; };
} }
@@ -148,6 +153,7 @@ class Trip {
DateTime? createdAt, DateTime? createdAt,
DateTime? updatedAt, DateTime? updatedAt,
String? status, String? status,
String? imageUrl,
}) { }) {
return Trip( return Trip(
id: id ?? this.id, id: id ?? this.id,
@@ -162,6 +168,7 @@ class Trip {
createdAt: createdAt ?? this.createdAt, createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt, updatedAt: updatedAt ?? this.updatedAt,
status: status ?? this.status, status: status ?? this.status,
imageUrl: imageUrl ?? this.imageUrl,
); );
} }
@@ -236,4 +243,4 @@ class Trip {
@override @override
int get hashCode => id.hashCode; int get hashCode => id.hashCode;
} }