Internationalization (i18n) is an essential feature for developing multilingual applications. In this tutorial, we will explore how to implement i18n in Flutter using the GetX framework. GetX is a powerful state management and navigation solution that offers effortless integration for various functionalities, including i18n.
First, we need to add the get package to our pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
get: ^4.1.4
Next, let's create a new directory called lang in the project root. Inside this directory, we'll create a file for each supported language. For example, if we want to support English and Spanish, we'll create two files: en_US.dart and es_ES.dart.
In each language file, we define a Map with key-value pairs representing the translations. Here's an example of the English language file (en_US.dart):
Map<String, String> enUS = {
'title': 'Flutter GetX i18n Tutorial',
'welcome_message': 'Welcome to the GetX i18n tutorial!',
};
Similarly, we define the translations for other supported languages in their respective files.
Now, let's create a bindings class that will initialize the i18n functionality. In the lib directory, create a new file called bindings.dart. Inside this file, create a class called TranslationBindings and add the following code:
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:your_project_name/lang/en_US.dart'; // Import the language files
class TranslationBindings extends Bindings {
@override
void dependencies() {
Get.lazyPut(() => TranslationService());
Get.lazyPut(() => Locale('en', 'US')); // Change the locale based on the user's preference
}
}
class TranslationService extends GetxService {
final fallbackLocale = Locale('en', 'US');
final locales = {'en': 'en_US', 'es': 'es_ES'};
final RxString _locale = ''.obs;
String get locale => _locale.value;
set locale(String value) {
if (locales.containsKey(value)) {
_locale.value = value;
Get.updateLocale(Locale(value));
}
}
String translate(String key) {
final locale = locales[Get.locale.languageCode] ?? fallbackLocale;
final translations = {
'en_US': enUS, // Import the language files
'es_ES': esES,
};
return translations[locale][key] ?? '';
}
}
In the above code snippet, we first import the language files for translation. Then, we define the TranslationBindings
class, which extends the Bindings
class from the GetX package. Inside the dependencies()
method, we use Get.lazyPut()
to lazily instantiate the TranslationService
and the default Locale
of 'en_US'.
The TranslationService
class is responsible for managing the translation functionality. It stores the current locale using a RxString
. The translate()
method retrieves the appropriate translation based on the current locale and the provided key.
Finally, we need to add the bindings and initialize the translation service in the main application. In the main.dart file, add the following code:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final TranslationService translationService = Get.put(TranslationService());
@override
Widget build(BuildContext context) {
return GetMaterialApp(
title: translationService.translate('title'),
locale: Locale(translationService.locale),
fallbackLocale: Locale(translationService.fallbackLocale),
translations: translationService,
initialBinding: TranslationBindings(),
home: HomeScreen(),
);
}
}
Here, we create an instance of the TranslationService
and add it as a dependency using Get.put()
. We then configure the GetMaterialApp with the necessary i18n settings, including the translations, locale, and initialBinding.
Now, we can use the translation in any widget. Simply call the Translate()
widget from the Get package and provide the translation key as a parameter:
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Translate(
'title',
style: TextStyle(fontSize: 20),
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
Translate(
'welcome_message',
style: TextStyle(fontSize: 18),
),
),
],
),
),
);
}
}
In the above code snippet, we use the Translate()
widget to display the translated text dynamically. We pass the translation key as a parameter and can also provide additional styling options.
We have now successfully implemented i18n using GetX in Flutter. With GetX, managing translations becomes effortless and helps make your applications accessible to a global audience.