fast_i18n
Lightweight i18n solution. Use JSON files to create typesafe translations.
Getting Started
Step 1: Add dependencies
Step 2: Create JSON files
Create these files inside your lib
directory. Preferably in one common package like lib/i18n
.
Only files having the .i18n.json
file extension will be detected. You can configure it.
strings.i18n.json (default, fallback)
strings_de.i18n.json
Step 3: Generate the dart code
flutter pub run build_runner build
Step 4: Initialize
a) use device locale
b) use specific locale
Step 4a: Override 'supportedLocales'
This is optional but recommended.
Standard flutter controls (e.g. back button's tooltip) will also pick the right locale.
Step 4b: iOS configuration
File: ios/Runner/Info.plist
<key>CFBundleLocalizations</key>
<array>
<string>en</string>
<string>de</string>
</array>
Step 5: Use your translations
API
When the dart code has been generated, you will see some useful classes and functions
t
- the translate variable for simple translations
Translations.of(context)
- translations which reacts to locale changes
TranslationProvider
- App wrapper, used for Translations.of(context)
LocaleSettings.useDeviceLocale()
- use the locale of the device
LocaleSettings.setLocale('de')
- change the locale
LocaleSettings.setLocaleTyped(AppLocale.en)
- change the locale (typed version)
LocaleSettings.currentLocale
- get the current locale
LocaleSettings.currentLocaleTyped
- get the current locale (typed version)
LocaleSettings.locales
- get the supported locales
LocaleSettings.supportedLocales
- see step 4a
Configuration
All settings can be set in the build.yaml
file. Place it in the root directory.
Key | Type | Usage | Default |
---|---|---|---|
base_locale | String |
locale of default json | en |
input_directory | String |
path to input directory | null |
input_file_pattern | String |
input file pattern | .i18n.json |
output_directory | String |
path to output directory | null |
output_file_pattern | String |
output file pattern | .g.dart |
translate_var | String |
translate variable name | t |
enum_name | String |
enum name | AppLocale |
key_case | camel , pascal , snake |
transform keys (optional) | null |
maps | List<String> |
entries which should be accessed via keys | [] |
FAQ
How do I add arguments?
Use the $
prefix.
In edge cases you can also wrap it with ${...}
.
How can I access translations using maps?
Define the maps in your build.yaml
.
Keep in mind that all nice features like autocompletion are gone.
strings.i18n.json
build.yaml
Now you can access the translations via keys:
Can I use lists?
Lists are fully supported. You can also put lists or maps inside lists!