[Flutter] Translations, internationalisation with GetX package

As applications are actually spread around the world, a common task to implement when developing your app (mobile, web or desktop), is to setup a multi-language option

In Flutter, it can be done easily with the GetX Package (a useful package that provides a lot more services ! You should take a look if you don't know this package: GetX package on pub.dev.

The implementation steps are the following:


1-Add GetX package to your solution

You can do it the traditional way you like. For instance with "Pub Assist" extension:

Shift+CMD+P > Pub asssist: add/upgrade > get


2-Use a GetMaterialApp

Important step, do not forget to use the GetMaterialApp classe instead of Flutter's MaterialApp:

@override
Widget build(BuildContext context) {
return GetMaterialApp(


3-Add a translation file

Next you have to add a class that will embed all your strings declaration / translations. This class must extends the GetX's Translation class. Here is an example:

class AppTranslations extends Translations {
@override
Map<String, Map<String, String>> get keys => {
// --------- ENGLISH ----------
'en': {
'Title': 'My title (EN)',
'CustomMsg': "This is an english message",
},
// --------- FRENCH ----------
'fr_FR': {
'Title': 'Mon titre (FR)',
'CustomMsg': "C'est un message en FR",
}
};
}

The class contains a map of Language, List of translations <key: translation>.


4-Setup the localisation in your GetMaterialApp

Some localisation's parameters are available from the GetMaterialApp class. This is where you have to link the app with your own translation class:

@override
Widget build(BuildContext context) {
return GetMaterialApp(
// !! GetMaterialApp
translations: AppTranslations(), // <------ set your app translation class
fallbackLocale: const Locale('en'),
locale: Get.deviceLocale, //const Locale('fr'),

You can notice the GetX helper:

- Get.deviceLocale => returns the current system Locale object


5-Use translations in your code

> for a simple translation, use '.tr' property:

title: 'Title'.tr,

> for a translation with parameters

import 'package:get/get.dart';


Map<String, Map<String, String>> get keys => {
    'en_US': {
        'logged_in': 'logged in as @name with email @email',
    },
    'es_ES': {
       'logged_in': 'iniciado sesiĆ³n como @name con e-mail @email',
    }
};

Text('logged_in'.trParams({
  'name': 'Jhon',
  'email': 'jhon@example.com'
  }));


Take a look at the official documentation:

https://pub.dev/packages/get#using-translations



Comments

Popular posts from this blog

EMGU with Xamarin Forms guide [part 1]

[Xamarin Forms] Custom bottom bordered entry (iOS & Android)

Xamarin.Forms device unique ID...