Localization
Learn to make our app more accessible by making it multilingual.
Introduction to localization using GetX
Today’s world is truly global and applications have far more reach than a single country and language. Modern apps must be multilingual to be used by everyone irrespective of the person’s language. Let us understand how GetX helps us implement localization in our apps.
GetX provides us a place to store the string translations in the form of the Translations
class. It also provides extensions to translate the text in the app based on its locale (language). We can define the app’s locale and load the translations in GetMaterialApp
. And, update the locale at any time with a single method. Further in this lesson, we will discuss each feature in detail.
The Translations
class
Translations
class is the place to store the translations for the text that will be used in our app. We extend it and place all the data in its keys
map. The translations are categorized by the language. So for each language, we maintain a map of all the strings to their translations in that language. The strings that are used as keys should be consistent for every language. For example, in the code below, the key greeting
is the same in every language. Only its value, i.e., the translation is different in each map.
class TranslationData extends Translations {@overrideMap<String, Map<String, String>> get keys => {'en_US': {'greeting': 'Greetings, %s!','welcome': 'Welcome to the app, @name!','status': 'Your account status is: @status','product': 'Product','products': 'I have @count products',},'de_DE': {'greeting': 'Herzlich willkommen, %s!','welcome': 'Willkommen in der App, @name!','status': 'Ihr Kontostatus lautet: @status','product': 'Produkt','products': 'Ich habe @count Produkte',},'fr_FR': {'greeting': 'Salutations, %s!','welcome': 'Bienvenue dans l\'application, @name!','status': 'Votre statut de compte est: @status','product': 'Produit','products': 'J\'ai @count produits',},'es_ES': {'greeting': '¡Saludos, %s!','welcome': 'Bienvenido/a a la aplicación, @name!','status': 'El estado de tu cuenta es: @status','product': 'Producto','products': 'Tengo @count productos',},'ja_JP': {'greeting': 'こんにちは、%sさん!','welcome': 'アプリへようこそ、@nameさん!','status': 'アカウントのステータスは: @statusです','product': '製品','products': '私は@count個の製品を持っています',},};}
keys
maps a language and country code (en_US
stands for English-USA) to another map that contains the key-value pairs of localized strings.
Loading translations and defining locale
Now that we have our translations data in place, we can load it in GetMaterialApp
that makes it available throughout the application.
GetMaterialApp(translations: TranslationData(),);
Next ...