feat: integrate ErrorService for consistent error display and standardize bloc error messages.

This commit is contained in:
Van Leemput Dayron
2025-12-02 13:59:40 +01:00
parent 1e70b9e09f
commit 6757cb013a
24 changed files with 927 additions and 608 deletions

View File

@@ -19,7 +19,9 @@
/// The component automatically loads account data when initialized and
/// provides a clean interface for managing group-based expenses.
library;
import 'package:flutter/material.dart';
import '../../services/error_service.dart';
import 'package:travel_mate/blocs/user/user_bloc.dart';
import '../../models/account.dart';
import '../../blocs/account/account_bloc.dart';
@@ -45,10 +47,10 @@ class _AccountContentState extends State<AccountContent> {
/// Repository for group data operations used for navigation
final _groupRepository = GroupRepository(); // Ajouter cette ligne
@override
@override
void initState() {
super.initState();
// Load immediately without waiting for the next frame
WidgetsBinding.instance.addPostFrameCallback((_) {
_loadInitialData();
@@ -56,13 +58,13 @@ class _AccountContentState extends State<AccountContent> {
}
/// Loads the initial account data for the current user.
///
///
/// Retrieves the current user from UserBloc and loads their accounts
/// using the AccountBloc. Handles errors gracefully with error display.
void _loadInitialData() {
try {
final userState = context.read<UserBloc>().state;
if (userState is user_state.UserLoaded) {
final userId = userState.user.id;
context.read<AccountBloc>().add(LoadAccountsByUserId(userId));
@@ -70,65 +72,50 @@ class _AccountContentState extends State<AccountContent> {
throw Exception('User not connected');
}
} catch (e) {
ErrorContent(
message: 'Error loading accounts: $e',
onRetry: () {},
);
ErrorContent(message: 'Error loading accounts: $e', onRetry: () {});
}
}
/// Navigates to the group expenses page for a specific account.
///
///
/// Retrieves the group associated with the account and navigates to
/// the group expenses management page. Shows error messages if the
/// group cannot be found or if navigation fails.
///
///
/// Args:
/// [account]: The account to navigate to for expense management
Future<void> _navigateToGroupExpenses(Account account) async {
try {
// Retrieve the group associated with the account
final group = await _groupRepository.getGroupByTripId(account.tripId);
if (group != null && mounted) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => GroupExpensesPage(
account: account,
group: group,
),
builder: (context) =>
GroupExpensesPage(account: account, group: group),
),
);
} else {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Group not found for this account'),
backgroundColor: Colors.red,
),
);
ErrorService().showError(message: 'Group not found for this account');
}
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error loading group: $e'),
backgroundColor: Colors.red,
),
);
ErrorService().showError(message: 'Error loading group: $e');
}
}
}
/// Builds the main widget for the account content page.
///
///
/// Creates a responsive UI that handles different user and account states:
/// - Shows loading indicator for user authentication
/// - Displays error content for user errors
/// - Builds account content based on account loading states
///
///
/// Returns:
/// Widget representing the complete account page UI
@override
@@ -139,9 +126,12 @@ class _AccountContentState extends State<AccountContent> {
listener: (context, accountState) {
if (accountState is AccountError) {
ErrorContent(
message: 'Erreur de chargement des comptes : ${accountState.message}',
message:
'Erreur de chargement des comptes : ${accountState.message}',
onRetry: () {
context.read<AccountBloc>().add(LoadAccountsByUserId(user.id));
context.read<AccountBloc>().add(
LoadAccountsByUserId(user.id),
);
},
);
}
@@ -156,10 +146,7 @@ class _AccountContentState extends State<AccountContent> {
loadingWidget: const Scaffold(
body: Center(child: CircularProgressIndicator()),
),
errorWidget: ErrorContent(
message: 'User error',
onRetry: () {},
),
errorWidget: ErrorContent(message: 'User error', onRetry: () {}),
noUserWidget: const Scaffold(
body: Center(child: Text('Utilisateur non connecté')),
),
@@ -167,16 +154,16 @@ class _AccountContentState extends State<AccountContent> {
}
/// Builds the main content based on the current account state.
///
///
/// Handles different account loading states and renders appropriate UI:
/// - Loading: Shows circular progress indicator with loading message
/// - Error: Displays error content with retry functionality
/// - Loaded: Renders the accounts list or empty state message
///
///
/// Args:
/// [accountState]: Current state of account loading
/// [userId]: ID of the current user for reload operations
///
///
/// Returns:
/// Widget representing the account content UI
Widget _buildContent(AccountState accountState, String userId) {
@@ -188,11 +175,11 @@ class _AccountContentState extends State<AccountContent> {
CircularProgressIndicator(),
SizedBox(height: 16),
Text('Chargement des comptes...'),
],
),
],
),
);
}
}
if (accountState is AccountError) {
return ErrorContent(
message: 'Erreur de chargement des comptes...',
@@ -223,15 +210,15 @@ class _AccountContentState extends State<AccountContent> {
),
],
),
);
);
}
/// Builds the empty state widget when no accounts are found.
///
///
/// Displays a user-friendly message explaining that accounts are
/// automatically created when trips are created. Shows an icon
/// and informative text to guide the user.
///
///
/// Returns:
/// Widget representing the empty accounts state
Widget _buildEmptyState() {
@@ -241,7 +228,11 @@ class _AccountContentState extends State<AccountContent> {
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.account_balance_wallet, size: 80, color: Colors.grey),
const Icon(
Icons.account_balance_wallet,
size: 80,
color: Colors.grey,
),
const SizedBox(height: 16),
const Text(
'No accounts found',
@@ -260,15 +251,15 @@ class _AccountContentState extends State<AccountContent> {
}
/// Builds a scrollable list of user accounts with pull-to-refresh functionality.
///
///
/// Creates a RefreshIndicator-wrapped ListView that displays all user accounts
/// in card format. Includes a header with title and description, and renders
/// each account using the _buildSimpleAccountCard method.
///
///
/// Args:
/// [accounts]: List of accounts to display
/// [userId]: Current user ID for refresh operations
///
///
/// Returns:
/// Widget containing the accounts list with pull-to-refresh capability
Widget _buildAccountsList(List<Account> accounts, String userId) {
@@ -280,28 +271,28 @@ class _AccountContentState extends State<AccountContent> {
child: ListView(
padding: const EdgeInsets.all(16),
children: [
...accounts.map((account) {
...accounts.map((account) {
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: _buildSimpleAccountCard(account),
);
})
}),
],
)
),
);
}
/// Builds an individual account card with account information.
///
///
/// Creates a Material Design card displaying account details including:
/// - Account name with color-coded avatar
/// - Member count and member names (up to 2 displayed)
/// - Navigation capability to group expenses
/// - Error handling for card rendering issues
///
///
/// Args:
/// [account]: Account object containing account details
///
///
/// Returns:
/// Widget representing a single account card
Widget _buildSimpleAccountCard(Account account) {
@@ -309,9 +300,10 @@ class _AccountContentState extends State<AccountContent> {
final colors = [Colors.blue, Colors.purple, Colors.green, Colors.orange];
final color = colors[account.name.hashCode.abs() % colors.length];
String memberInfo = '${account.members.length} member${account.members.length > 1 ? 's' : ''}';
String memberInfo =
'${account.members.length} member${account.members.length > 1 ? 's' : ''}';
if(account.members.isNotEmpty){
if (account.members.isNotEmpty) {
final names = account.members
.take(2)
.map((m) => m.pseudo.isNotEmpty ? m.pseudo : m.firstName)
@@ -324,15 +316,19 @@ class _AccountContentState extends State<AccountContent> {
child: ListTile(
leading: CircleAvatar(
backgroundColor: color,
child: const Icon(Icons.account_balance_wallet, color: Colors.white),
child: const Icon(
Icons.account_balance_wallet,
color: Colors.white,
),
),
title: Text(
account.name,
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
subtitle: Text(memberInfo),
trailing: const Icon(Icons.chevron_right),
onTap: () => _navigateToGroupExpenses(account), // Navigate to group expenses
onTap: () =>
_navigateToGroupExpenses(account), // Navigate to group expenses
),
);
} catch (e) {
@@ -341,8 +337,8 @@ class _AccountContentState extends State<AccountContent> {
child: const ListTile(
leading: Icon(Icons.error, color: Colors.red),
title: Text('Display error'),
)
),
);
}
}
}
}