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 { /// Creates a new [ThemeBloc] with default theme state. /// /// Registers event handlers for theme changes and loading saved preferences. ThemeBloc() : super(const ThemeState()) { on(_onThemeChanged); on(_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 _onThemeChanged( ThemeChanged event, Emitter 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 _onThemeLoadRequested( ThemeLoadRequested event, Emitter 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)); } } }