Before starting our blog topic Multi-lingual in Flutter, let’s discuss multilingually. What is multilingual? and why do we need it in Flutter application development?
Multilingual is related to the multiple languages in that an application is supported.
Whenever we develop any application, for accessing a large number of users of different countries or different communities, your application must support the language that users understand.
With the support of multiple languages, you can ensure a large number of user groups for your application.
Let’s start the implementation of the Multi-lingual In Flutter project and get to know how we improvise the user experience of the Flutter application.
You may also check our Flutter app development services page.
1. Add the localization package into pubsec.yaml folder
1 2 3 4 5 6 7 8 9 10 11 12 |
dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter dev_dependencies: flutter_test: sdk: flutter intl: ^0.17.0-nullsafety.2 |
We have added the flutter_localization dependency and int1 dev dependency for the null check. You can add the updated version on int1 dependency.
2. Add the Strings files in assests folder.
Now, we will add the different JSON files in the assets folder, which consists of the strings values for the application.
We have added the “en.json” & “ar.json” files, as we are doing with Arabic and English translation. You can add multiple files as per your requirements.
1 2 3 4 5 6 7 8 9 10 11 12 |
// ar.json file { "app_title": "عرض توضيحي متعدد اللغات", "main_title": "لوريم إيبسوم هو ببساطة نص شكلي يستخدم في صناعة الطباعة والتنضيد. كان Lorem Ipsum هو النص الوهمي القياسي في الصناعة منذ القرن الخامس عشر الميلادي ، عندما أخذت طابعة غير معروفة لوحًا من النوع وتدافعت عليه لصنع كتاب عينة من النوع. لقد صمد ليس فقط لخمسة قرون ، ولكن أيضًا القفزة في التنضيد الإلكتروني ، وظل دون تغيير جوهري. تم نشره في الستينيات من القرن الماضي مع إصدار أوراق Letraset التي تحتوي على مقاطع Lorem Ipsum ، ومؤخرًا مع برامج النشر المكتبي مثل Aldus PageMaker بما في ذلك إصدارات Lorem Ipsum." } // en.json file { "app_title": "Multilingual Demo", "main_title": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." } |
3. Create a Language translation file.
In this post, we will look at the process of translating a language into English. We will create a translation file, which will be used to fetch the data from the assets locale directory.
When the string name does not match with existing string then it will return the blank strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class LanguageTranslation { late Locale locale; static Map<dynamic, dynamic> _localizedValues = new Map(); LanguageTranslation(Locale locale) { this.locale = locale; _localizedValues = new Map(); } static LanguageTranslation? of(BuildContext context) { return Localizations.of<LanguageTranslation>(context, LanguageTranslation); } String value(String key) { return _localizedValues[key] ?? '** $key not found'; } static Future<LanguageTranslation> load(Locale locale) async { LanguageTranslation translations = new LanguageTranslation(locale); String jsonContent = await rootBundle.loadString("assets/locale/${locale.languageCode}.json"); _localizedValues = json.decode(jsonContent); return translations; } get currentLanguage => locale.languageCode; } |
The LanguageDelegate class will load the LanguageTranslation class whenever a locale changes. The Delegate class check the localization is supported or not and load the language translation class when it changes. It will also extend the “LocalizationDelegate” class if the locale does not change.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class TranslationsDelegate extends LocalizationsDelegate<LanguageTranslation> { const TranslationsDelegate(); @override bool isSupported(Locale locale) => ['en', 'ar'].contains(locale.languageCode); @override Future<LanguageTranslation> load(Locale locale) => LanguageTranslation.load(locale); @override bool shouldReload(TranslationsDelegate old) => false; } |
4. Use the localization in main.dart
In the material app, we will add the support for the delegate class and translation class and pass it to the parent widget:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
localizationsDelegates: [ const TranslationsDelegate(), GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ], supportedLocales: [ const Locale('en', ''), const Locale('ar', ''), ], localeResolutionCallback: (locale, supportedLocales) { for (var supportedLocaleLanguage in supportedLocales) { if (supportedLocaleLanguage.languageCode == locale!.languageCode && supportedLocaleLanguage.countryCode == locale.countryCode) { return supportedLocaleLanguage; } } return supportedLocales.first; }, home: MyHomePage(title: ''), |
Now, everywhere in the whole app, you should use LanguageTranslation’s “value” method to get the string values according to the locale.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// for getting the string values on the basis of locale. LanguageTranslation.of(context)!.text('main_title') // You can use following method to update the locale void onLocaleChange(Locale locale) async { setState(() { LanguageTranslation.load(locale); }); } // calling the method for locale change onLocaleChange(const Locale("en")); |
Output :
Conclusion:
You can use multi-lingual to enhance the user experience and increase the number of users for your application of different languages
I hope this blog helps you to understand the basic uses of the Multi-lingual In Flutter.
Thank you for reading!!
For more information, you can visit the Dev Console.