Files
TravelMate/lib/blocs/theme/theme_bloc.dart
Dayron 2faf37f145 Enhance model and service documentation with detailed comments and descriptions
- Updated Group, Trip, User, and other model classes to include comprehensive documentation for better understanding and maintainability.
- Improved error handling and logging in services, including AuthService, ErrorService, and StorageService.
- Added validation and business logic explanations in ExpenseService and TripService.
- Refactored method comments to follow a consistent format across the codebase.
- Translated error messages and comments from French to English for consistency.
2025-10-30 15:56:17 +01:00

62 lines
2.1 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'theme_event.dart';
import 'theme_state.dart';
/// BLoC for managing application theme preferences.
///
/// This BLoC handles theme-related events and manages the application's
/// theme mode (light, dark, or system). It persists theme preferences
/// using SharedPreferences for consistency across app sessions.
class ThemeBloc extends Bloc<ThemeEvent, ThemeState> {
/// Creates a new [ThemeBloc] with default theme state.
///
/// Registers event handlers for theme changes and loading saved preferences.
ThemeBloc() : super(const ThemeState()) {
on<ThemeChanged>(_onThemeChanged);
on<ThemeLoadRequested>(_onThemeLoadRequested);
}
/// Handles [ThemeChanged] events.
///
/// Updates the theme mode and persists the preference to local storage.
/// This ensures the theme choice is remembered across app restarts.
Future<void> _onThemeChanged(
ThemeChanged event,
Emitter<ThemeState> emit,
) async {
emit(state.copyWith(themeMode: event.themeMode));
// Save the theme preference to persistent storage
final prefs = await SharedPreferences.getInstance();
await prefs.setString('themeMode', event.themeMode.toString());
}
/// Handles [ThemeLoadRequested] events.
///
/// Loads the saved theme preference from SharedPreferences and applies it.
/// If no preference is saved, the theme remains as system default.
Future<void> _onThemeLoadRequested(
ThemeLoadRequested event,
Emitter<ThemeState> emit,
) async {
final prefs = await SharedPreferences.getInstance();
final themeModeString = prefs.getString('themeMode');
if (themeModeString != null) {
ThemeMode themeMode;
switch (themeModeString) {
case 'ThemeMode.light':
themeMode = ThemeMode.light;
break;
case 'ThemeMode.dark':
themeMode = ThemeMode.dark;
break;
default:
themeMode = ThemeMode.system;
}
emit(state.copyWith(themeMode: themeMode));
}
}
}