Flutter translations with GetX

Today, I will show you how to deal with translations using the GetX package.

Flutter translations with GetX
Photo by Fili Santillán / Unsplash

GetX provide very nice internationalization tools where we can work with translations. Traditional usage, as the documentation says, is fairly straightforward, so today I'll show you a small tweak to help structure and handle multiple languages.

Step 1—create translations keys file

To begin with, we need to create a language file in which we will store all the translations, along with the keys that we will use in the code. The file name reflects the language name, e.g., Englishen.dart Inside this file, let's create a class with sample messages:

import 'translation_keys.dart' as translation;

class En {
  Map<String, String> get messages => {
        translation.title: 'Title',
        translation.subtitle: 'This is the subtitle',
        translation.withParam: 'Translation with param: hello @param'
      };
}
English translation file with example messages

Step 2—Add translation keys

The next step is to create a new file called,translation_keys.dart which will contain all the keys we will use in both the language files and inside the code. Since we only have three messages above, we need to add them to this file:

const title = 'title';
const subtitle = 'subtitle';
const withParam = 'withParam';
Translation keys

Step 3—Add configuration

The last step to make the translations work is to create a Messages class in which we will use our earlier translations, and this will be done in the messages.dart file:

class Messages extends Translations {
  @override
  Map<String, Map<String, String>> get keys => {
        'en_US': En().messages,
        'it_IT': It().messages,
      };
}
Messages class extended Translation from GetX

Of course, that's not enough, we also need to add the translation to the main class and replace it with this provided by GetX, which is called GetMaterialApp. In the main.dart file, we need to replace the MaterialApp class with the following code:

return GetMaterialApp(
      translations: Messages(),
      locale: const Locale('en', 'EN'),
      fallbackLocale: const Locale('es', 'ES'),
      home: Scaffold(
        body: SafeArea(
          child: Column(
            children: <Widget>[
              Text(translations.title.tr),
              Text(
                translations.withParam.trParams({'param': 'world'}),
              ),
            ],
          ),
        ),
      ),
    );
Main file with declared GetX Material class

As you can see in the translations key we provide our Messages class and below we can refer to our translation by keys defined earlier in the Text widget.


Thanks for reading ♥️♥️

If this article was helpful, please leave a comment or 👍