translateBlocMessage function
Translates a BLoC message key to a localized string using the provided localizations object.
This function provides a clean separation between BLoC (business logic) and UI (localization). BLoCs emit message keys, and the UI layer translates them using this helper.
Usage:
BlocListener<UserBloc, UserState>(
listener: (context, state) {
if (state.status == UserStatus.success && state.message != null) {
final localizations = UserCompanyLocalizations.of(context)!;
HelperFunctions.showMessage(
context,
translateBlocMessage(localizations, state.message!),
Colors.green,
);
}
},
child: // ... your UI
)
Parameters:
localizations: The localizations object (e.g., UserCompanyLocalizations, CoreLocalizations)messageKey: The message key to translate (e.g., 'userUpdateSuccess')params: Optional map of parameters to replace in the translated message
Returns: The translated string, or the original key if no translation is found
Implementation
String translateBlocMessage(
dynamic localizations,
String messageKey, {
Map<String, dynamic>? params,
}) {
try {
// Use a type-safe approach without using mirrors
String? translatedMessage = _getTranslationFromLocalizations(
localizations,
messageKey,
params,
);
return translatedMessage ?? messageKey;
} catch (e) {
debugPrint('Translation error for key "$messageKey": $e');
return messageKey; // Fallback to the key itself
}
}