Flutter multi language without use package.
English language | Arabic language |
---|---|
- create file as assets
assets
└── lang
├── en.json
└── ar.json
- set key and value
- en.json
{
"title_Home": "Flutter Demo Home Page",
"counter": "You have pushed the button this many times:",
"tooltip_Increment": "Increment"
}
- ar.json
{
"title_Home": "فلاتر ديو صفحة الرئيسية",
"counter": "لقد ضغطت على الزر عدة مرات:",
"tooltip_Increment": "زيادة"
}
- Go to pubspec.yaml file.
- add flutter_localizations as dependencies.
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
- import file assets lang
assets:
- assets/lang/
- create AppLocalizations and AppLocalizationsDelegate classes.
class AppLocalizations {
late Locale locale;
late Map<String, String> _valueText;
AppLocalizations(this.locale);
static AppLocalizations of(BuildContext context) {
return Localizations.of(context, AppLocalizations);
}
static const LocalizationsDelegate<AppLocalizations> delegate =
AppLocalizationsDelegate();
Future loadTranslateFile() async {
String _langFile =
await rootBundle.loadString('assets/lang/${locale.languageCode}.json');
Map<String, dynamic> _json = jsonDecode(_langFile);
_valueText = _json.map((key, value) => MapEntry(key, value.toString()));
}
String getTranslate(String key) {
return _valueText[key]!;
}
}
class AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
const AppLocalizationsDelegate();
@override
bool isSupported(Locale locale) {
return ['en', 'ar'].contains(locale.languageCode);
}
@override
Future<AppLocalizations> load(Locale locale) async {
AppLocalizations appLocalizations = AppLocalizations(locale);
await appLocalizations.loadTranslateFile();
return appLocalizations;
}
@override
bool shouldReload(covariant AppLocalizationsDelegate old) => false;
}
- injection appLocalizations delegate in root widget.
MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: const [
Locale('en', ''),
Locale('ar', ''),
],
// check Locale supported
localeResolutionCallback:
(Locale? deviceLocale, Iterable<Locale> supportedLocales) =>
deviceLocale != null &&
['en', 'ar'].contains(deviceLocale.languageCode)
? deviceLocale
: supportedLocales.first,
home: const MyHomePage(),
);
- use AppLocalizations to get text.
AppLocalizations.of(context).getTranslate(keyJsonFile);
AppLocalizations.of(context).getTranslate('tooltip_Increment');
Thank's to read ,hope help you.