[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:
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:
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:
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:
> 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
Post a Comment