translate method
Translates the string using the provided context or global translator.
This method attempts to translate the string based on the current locale context. It first checks for a global translator function, then falls back to the context-based localization system.
Parameters:
context
- The BuildContext used to determine the current localeglobalTranslator
- Optional custom translation function for special cases
Returns:
- A translated string if available, otherwise the original string
Translation Flow
- If
globalTranslator
is provided, use it to translate the string - Otherwise, use
AppLocalizations.of(context)
to get the current locale - Call the
translate
method on the localization instance - If translation fails, return the original string as fallback
Global Translator Usage
Global translators are useful for:
- Dynamic content that can't be pre-translated
- Custom translation logic or external translation services
- Testing scenarios with mock translations
- Overriding default translations for specific use cases
Example
// Basic translation
final greeting = 'hello'.translate(context);
// With custom translator
final customGreeting = 'hello'.translate(
context,
globalTranslator: (key) {
switch (key) {
case 'hello':
return 'Custom Hello';
default:
return key;
}
},
);
// In a widget
Text('payment_amount'.translate(context))
Implementation
String translate(
BuildContext context, {
String Function(String p1)? globalTranslator,
}) {
if (globalTranslator != null) {
return globalTranslator(this);
} else {
return AppLocalizations.of(context)?.translate(this) ?? this;
}
}