translate method

String translate(
  1. BuildContext context, {
  2. String globalTranslator(
    1. String p1
    )?,
})

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 locale
  • globalTranslator - Optional custom translation function for special cases

Returns:

  • A translated string if available, otherwise the original string

Translation Flow

  1. If globalTranslator is provided, use it to translate the string
  2. Otherwise, use AppLocalizations.of(context) to get the current locale
  3. Call the translate method on the localization instance
  4. 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;
  }
}