Easily Localize without BuildContext
- Create a folder in
assets/
with nameLang
. - Create json files to define translation in that folder with this format
{langCode}-{countryCode}.json
.
For example:
- In these json files, format should be like this:
{
"example key" : "Example",
"other key" : "Others"
}
- Assign these assets in
pubspec.yaml
.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, aPdd an assets section, like this:
assets:
- assets/lang/ # <---- add this
- In main() method, initialize
IndependentLocalization
like this:
WidgetsFlutterBinding.ensureInitialized();
await IndependentLocalization(
fallbackLocale: LocalizationManager.defaultLocale,
localesJson: await LocalizationManager.localeJson)
.initialize();
localesJson
must be loaded withrootBundle
fromassets
.
static Future<Map<Locale, String>> get localeJson async => {
LOCALE_JP: await rootBundle.loadString('assets/lang/ja-JP.json'),
LOCALE_EN: await rootBundle.loadString('assets/lang/en-US.json'),
LOCALE_CH_CN: await rootBundle.loadString('assets/lang/zh-CN.json'),
LOCALE_CH_TW: await rootBundle.loadString('assets/lang/zh-TW.json'),
};
Done!. You are ready to run it.
Usage: "sometext".tr
or tr("sometext")
Method | Description |
---|---|
Get singleton instance | IndependentLocalization.instance |
Get current language | IndependentLocalization.instance!.currentLocale |
Change current language | IndependentLocalization.instance!.changeLocale(locale) |