refactor: improve locale management and initialization in LocaleBloc and LocalizationModule

This commit is contained in:
Achintha Isuru
2026-01-28 10:09:43 -05:00
parent f5c2c0757d
commit ed588e0ec7
3 changed files with 35 additions and 27 deletions

View File

@@ -11,23 +11,29 @@ import 'locale_state.dart';
/// It coordinates the flow between user language requests and persistent storage
/// using [SetLocaleUseCase] and [GetLocaleUseCase].
class LocaleBloc extends Bloc<LocaleEvent, LocaleState> {
final GetLocaleUseCase getLocaleUseCase;
final SetLocaleUseCase setLocaleUseCase;
/// Creates a [LocaleBloc] with the required use cases.
LocaleBloc({required this.getLocaleUseCase, required this.setLocaleUseCase})
: super(LocaleState.initial()) {
on<ChangeLocale>(_onChangeLocale);
on<LoadLocale>(_onLoadLocale);
/// Initial event
add(const LoadLocale());
}
/// Use case for retrieving the saved locale.
final GetLocaleUseCase getLocaleUseCase;
/// Use case for saving the selected locale.
final SetLocaleUseCase setLocaleUseCase;
/// Handles the [ChangeLocale] event by saving it via the use case and emitting new state.
Future<void> _onChangeLocale(
ChangeLocale event,
Emitter<LocaleState> emit,
) async {
// 1. Update slang settings
LocaleSettings.setLocaleRaw(event.locale.languageCode);
await LocaleSettings.setLocaleRaw(event.locale.languageCode);
// 2. Persist using Use Case
await setLocaleUseCase(event.locale);
@@ -47,7 +53,7 @@ class LocaleBloc extends Bloc<LocaleEvent, LocaleState> {
Emitter<LocaleState> emit,
) async {
final Locale? savedLocale = await getLocaleUseCase();
final Locale locale = const Locale('es');
final Locale locale = savedLocale ?? const Locale('es');
LocaleSettings.setLocaleRaw(locale.languageCode);

View File

@@ -18,25 +18,25 @@ class LocalizationModule extends Module {
i.addInstance<SharedPreferencesAsync>(SharedPreferencesAsync());
// Data Sources
i.addSingleton<LocaleLocalDataSource>(
i.addLazySingleton<LocaleLocalDataSource>(
() => LocaleLocalDataSourceImpl(i.get<SharedPreferencesAsync>()),
);
// Repositories
i.addSingleton<LocaleRepositoryInterface>(
i.addLazySingleton<LocaleRepositoryInterface>(
() => LocaleRepositoryImpl(i.get<LocaleLocalDataSource>()),
);
// Use Cases
i.addSingleton<GetLocaleUseCase>(
i.addLazySingleton<GetLocaleUseCase>(
() => GetLocaleUseCase(i.get<LocaleRepositoryInterface>()),
);
i.addSingleton<SetLocaleUseCase>(
i.addLazySingleton<SetLocaleUseCase>(
() => SetLocaleUseCase(i.get<LocaleRepositoryInterface>()),
);
// BLoCs
i.addSingleton<LocaleBloc>(
i.add<LocaleBloc>(
() => LocaleBloc(
getLocaleUseCase: i.get<GetLocaleUseCase>(),
setLocaleUseCase: i.get<SetLocaleUseCase>(),