I'm building a Flutter app and want to support multiple languages, specifically English (en) and Malayalam (ml). I am using the GetX package for state management and routing, and I want users to dynamically switch languages within the app.
My requirements: Support for English and Malayalam.
User can switch language at runtime (e.g., using a dropdown or button).
Use GetX localization features instead of intl or flutter_localizations manually.
create a dart file for your translations e.g app_translations.dart
and define your translations in it like this:
class AppTranslations extends Translations {
@override
Map<String, Map<String, String>> get keys => {
// English Translations
'en_US': {
'app_title': 'My App',
'welcome_message': 'Welcome to MY App',
},
// Malayalam Translations
'ml_IN': {
'app_title': 'IN Malayalam',
'welcome_message': 'Welcome message in Malayalam',
},
}
create Object of this class and provide it to Material app like this:
Widget build(BuildContext context) {
return GetMaterialApp(
// Localization settings
translations: AppTranslations(), // Your translations class
locale: initialLocale, // initialLocale you can get it from local storage for persistent locale settings.
supportedLocales: const [ // Your supported Locales
Locale('en', 'US'),
Locale('ml', 'IN'),
],
home: HomeScreen(),
);
}
Then in the app you can use it like this:
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('app_title'.tr), // Translated AppBar title
),
body: Center(
child: Text(
'welcome_message'.tr, // Using .tr to get the translated string
),
),
);
}
}
and you can switch the language by the following method:
Get.updateLocale(newLocale);