Plugin:
Dependency:
flutter_localizations:
sdk: flutter
import 'package:localization/generated/i18n.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
MaterialApp(
title: 'Localization Demo',
localizationsDelegates: [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: S.delegate.supportedLocales,
home: Scaffold(
body: HomePage(),
));
Plugin will help you generate English
arb file automatically.
File will be located at res/values/strings_en.arb
.
{
"localization_demo": "Localization Demo",
"button": "Button"
}
You can now refer the values.
AppBar(
title: Text(S.of(context).localization_demo),
backgroundColor: Colors.green,
)
Adding this delegate can help us to change locale efficiently.
class SpecifiedLocalizationDelegate extends LocalizationsDelegate<S> {
final Locale overriddenLocale;
const SpecifiedLocalizationDelegate(this.overriddenLocale);
@override
bool isSupported(Locale locale) => overriddenLocale != null;
@override
Future<S> load(Locale locale) =>
GeneratedLocalizationsDelegate().load(overriddenLocale);
@override
bool shouldReload(SpecifiedLocalizationDelegate old) => true;
}
Initialize it with null locale and put into localizationsDelegates
_localeOverrideDelegate = SpecifiedLocalizationDelegate(null);
localizationsDelegates: [
_localeOverrideDelegate,
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
Reassign it when the application's locale changed.
_localeOverrideDelegate = SpecifiedLocalizationDelegate(newLocale);