In this article video we will learnt how to localization flutter app to multi-languages, demonstrating how we can Localize a Flutter application and Also how To change the Language with RTL or LTR direction text and image, without Restarting the Application.
Also, this application is persisting the selected used shared_preferences package with button switcher between languages
شرح انشاء تطبيق فلاتر جديد مع شرح مختصر ل ملفات التطبق الاساسية
1.1-ٍStructure of lib file
images
pages [ home_page - settings_page - about_page ]
router [ custom_router ]
localization [ demo_localization - language_constants ]
lang [ ar.json - en.json - fa-json - hi.json ]
classes [ language ]
1.1-Add the packages in your pub and click Pub get
Note: Flutter sdk: ">=2.7.0 <3.0.0"
dependencies:
...
flutter_localizations:
sdk: flutter
shared_preferences: ^0.5.6+2
click pub get
1.2- create images file and add image
Note: in your pubspec add images directory path and click pub get
assets:
- images/
2- In lib/lang Create JSON files that contain localized texts for local languages:
Note: Json files must have the name of the locale and its content must be a json of key and value ONLY.
-ar.json
-en.json
-fa.json
-hi.json
Note: in your pubspec add json files directory and click pub get
assets:
....
- lib/lang/en.json
- lib/lang/fa.json
- lib/lang/ar.json
- lib/lang/hi.json
3-Add this code to main.dart file
3.1-Now, MyApp class add the delegate in MaterialApp, CupertinoApp and WidgetsApp and define a path where the translation json files
The next step is to setup the Localization delegates in your main.dart file. For that you need to specify the 3 delegates,and import package of flutter_localizations
#import_library
localizationsDelegates: [
// delegate from flutter_localization
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
4-Add supported languages
This setting is important to tell Flutter which languages your app is prepared to work with. We can do this by simply adding the Locale in the supportedLocales
supportedLocales: [
Locale("en", "US"),
Locale("fa", "IR"),
Locale("ar", "SA"),
Locale("hi", "IN")
],
5- locale Resolution
This step is importantwhen the device language is not supported by our app or work with a different translation for different countries to determine the active locale when the app runs
6- Use If method to chack error with CircularProgressIndicator
when app not find locale languages or there is an error
After that, difine _locale in the '_MyAppState' . and create methed of setLocale
Locale _locale;
setLocale(Locale locale) {
setState(() {
_locale = locale;
});
}
Now, In MyApp class add setLocale in static method to set new locale
static void setLocale(BuildContext context, Locale newLocale) {
_MyAppState state = context.findAncestorStateOfType<_MyAppState>();
state.setLocale(newLocale);
}
Call the locale: _locale, method in MaterialApp
7- DemoLocalization class
we need to create custom class called DemoLocalization in new file that contains the app’s strings translated into the locales that the app supports.
import 'package:flutter/cupertino.dart';
class DemoLocalization {
DemoLocalization(this.locale);
final Locale locale;
static DemoLocalization of(BuildContext context) {
return Localizations.of<DemoLocalization>(context, DemoLocalization);
}
//...
}
And we create load() function inside Future method with map.Json that will load the required JSON file according to locale languages from lang file.json #import_library
Map<String, String> _localizedValues;
Future<void> load() async {
String jsonStringValues =
await rootBundle.loadString('lib/lang/${locale.languageCode}.json');
Map<String, dynamic> mappedJson = json.decode(jsonStringValues);
_localizedValues =
mappedJson.map((key, value) => MapEntry(key, value.toString()));
}
Create translate method will return the localized string for given key
String translate(String key) {
return _localizedValues[key];
}
create static member for _DemoLocalizationsDelegate(); to have simple access to the delegate from Material App
static const LocalizationsDelegate<DemoLocalization> delegate =
_DemoLocalizationsDelegate();
7.1- _DemoLocalizationsDelegate class
Create _DemoLocalizationsDelegate class for control with selected languages that pass them from DemoLocalization class
in MyApp class inside localizationsDelegates add DemoLocalization.delegate, that load translated strings from language JSON files #import_library
7.2- language_constants file
This file to store and save the selected language according to the language code by SharedPreferences package. #import_library
after that we add didChangeDependencies method in MyApp class and call getLocale inside it #import_library
@override
void didChangeDependencies() {
getLocale().then((locale) {
setState(() {
this._locale = locale;
});
});
super.didChangeDependencies();
}
7.3- class Language
create Language class in new file to define items of language
class Language {
final int id;
final String flag;
final String name;
final String languageCode;
Language(this.id, this.flag, this.name, this.languageCode);
//...
}
7.4- Add the items of languages in static list
static List<Language> languageList() {
return <Language>[
Language(1, "🇦🇫", "فارسی", "fa"),
Language(2, "🇺🇸", "English", "en"),
Language(3, "🇸🇦", "اَلْعَرَبِيَّةُ", "ar"),
Language(4, "🇮🇳", "हिंदी", "hi"),
];
}
To get the code of country and flags and code languages from the link
http://www.lingoes.net/en/translator/langcode.htm
تعليقات
إرسال تعليق