Search code examples
fluttervariablesdartinternationalizationarb

Flutter 1.22 Internationalization with variable as key


I implemented the new (official) localization for Flutter (https://pascalw.me/blog/2020/10/02/flutter-1.22-internationalization.html) and everything is working fine, except that I don't know how to get the translation for a variable key.

The translation is in the ARB file, but how can I access it?

Normally I access translations using Translations.of(context).formsBack, but now I would like to get the translation of value["labels"]["label"].

Something like Translations.of(context).(value["labels"]["label"]) does not work of course.


Solution

  • I don't think this is possible with gen_l10n. The code that is generated by gen_l10n looks like this (somewhat abbreviated):

    /// The translations for English (`en`).
    class TranslationsEn extends Translations {
      TranslationsEn([String locale = 'en']) : super(locale);
    
      @override
      String get confirmDialogBtnOk => 'Yes';
    
      @override
      String get confirmDialogBtnCancel => 'No';
    }
    

    As you can see it doesn't generate any code to perform a dynamic lookup.

    For most cases code generation like this is a nice advantage since you get auto completion and type safety, but it does mean it's more difficult to accommodate these kinds of dynamic use cases.

    The only thing you can do is manually write a lookup table, or choose another i18n solution that does support dynamic lookups.

    A lookup table could look something like this. Just make sure you always pass in the current build context, so the l10n code can lookup the current locale.

    class DynamicTranslations {
      String get(BuildContext context, String messageId) {
        switch(messageId) {
          case 'confirmDialogBtnOk':
            return Translations.of(context).confirmDialogBtnOk;
          case 'confirmDialogBtnCancel':
            return Translations.of(context).confirmDialogBtnCancel;
          default:
            throw Exception('Unknown message: $messageId');
        }
      }
    }