• Stars
    star
    217
  • Rank 182,446 (Top 4 %)
  • Language
    Dart
  • License
    MIT License
  • Created over 6 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

I18n made easy, for Flutter!

flutter_i18n

All Contributors

I18n made easy, for Flutter!

Pub Package GitHub Actions


Table of contents

Why should you use flutter_i18n?

The main goal of flutter_i18n is to simplify the i18n process in Flutter. I would like to recreate the same experience that you have with the Angular i18n: simple json files, one for each language that you want to support.

Loaders

Loader is a class which loads your translations from specific source. You can easy override loader and create your own.

Available loaders:

Class name Purpose
FileTranslationLoader Loads translation files from JSON, YAML, TOML or XML format
LocalTranslationLoader Is a copy of FileTranslationLoader, but used to loads the files from the device storage instead of assets folder
NetworkFileTranslationLoader Loads translations from the remote resource
NamespaceFileTranslationLoader Loads translations from separate files
E2EFileTranslationLoader Special loader for solving isolates problem with flutter drive

FileTranslationLoader configuration

To use this library, you must create a folder in your project's root: the basePath. Some examples:

/assets/flutter_i18n (the default one)

/assets/i18n

/assets/locales

Inside this folder, you'll put the json, yaml, xml or toml files containing the translated keys. You have different options:

  • If you want to specify the country code

    basePath/{languageCode}_{countryCode}.json

  • If you want to specify the script code

    basePath/{languageCode}_{scriptCode}.json

  • If you want to specify both

    basePath/{languageCode}{scriptCode}${countryCode}_.json

  • otherwise

    basePath/{languageCode}.json

If the json file is not available, we will look for a yaml file with the same name. In case both exist, the json file will be used.

Of course, you must declare the subtree in your pubspec.yaml as assets:

flutter:
  assets:
    - {basePath}

The next step consist in the configuration of the localizationsDelegates; to use flutter_i18n, you should configure as follows:

localizationsDelegates: [
        FlutterI18nDelegate(
          translationLoader: FileTranslationLoader(...parameters...),
          missingTranslationHandler: (key, locale) {
            print("--- Missing Key: $key, languageCode: ${locale.languageCode}");
          },
        ),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
],
builder: FlutterI18n.rootAppBuilder() //If you want to support RTL.

Below you can find the name and description of the accepted parameters.

The useCountryCode parameter depends on the json configuration:

  • if you used the pattern {languageCode}_{countryCode}, useCountryCode must be true
  • if you used the pattern {languageCode}, useCountryCode must be false

The fallbackFile parameter was entroduces with the version 0.1.0 and provide a default language, used when the translation for the current running system is not provided. This should contain the name of a valid json file in assets folder.

The basePath parameter is optionally used to set the base path for translations. If this option is not set, the default path will be assets/flutter_i18n. This path must be the same path as the one defined in your pubspec.yaml.

The forcedLocale parameter is optionally used to force a locale instead finding the system one.

The decodeStrategies parameters is optionally used to choose witch kind of file you want to load. By default JSON, YAML and XML are enabled. If you use only one format, you can speed-up the bootstrap process using only the one you need.

If there isn't any translation available for the required key, even in the fallback file, the same key is returned.

NetworkFileTranslationLoader configuration

Behaviour of this loader very similar as FileTranslationLoader. The main difference that we load translations from NetworkAssetBundle instead of CachingAssetBundle.

Below you can find the name and description of the accepted parameters.

The baseUri parameter provide base Uri for your remote translations.

The useCountryCode parameter depends on the json configuration:

  • if you used the pattern {languageCode}_{countryCode}, useCountryCode must be true
  • if you used the pattern {languageCode}, useCountryCode must be false

The fallbackFile parameter provide a default language, used when the translation for the current running system is not provided.

The forcedLocale parameter is optionally used to force a locale instead finding the system one.

For example if your translation files located at https://example.com/static/en.json you should configure as follows:

localizationsDelegates: [
        FlutterI18nDelegate(translationLoader: 
          NetworkFileTranslationLoader(baseUri: Uri.https("example.com", "static")),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
],

NamespaceFileTranslationLoader configuration

Behaviour of this loader very similar as FileTranslationLoader. The main difference that we load translations from separate files per each language.

For example FileTranslationLoader format:

/assets/flutter_i18n/en.json

/assets/flutter_i18n/it.json

NamespaceFileTranslationLoader format:

/assets/flutter_i18n/en/home_screen.json

/assets/flutter_i18n/en/about_screen.json

/assets/flutter_i18n/it/home_screen.json

/assets/flutter_i18n/it/about_screen.json

Example configuration:

localizationsDelegates: [
        FlutterI18nDelegate(translationLoader: 
          NamespaceFileTranslationLoader(namespaces: ["home_screen", "about_screen"]),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
],

Below you can find the name and description of the accepted parameters.

The namespaces provide a list of filenames for the specific language directory.

The useCountryCode parameter depends on the json configuration:

  • if you used the pattern {languageCode}_{countryCode}, useCountryCode must be true
  • if you used the pattern {languageCode}, useCountryCode must be false

The fallbackDir provide a default language directory, used when the translation for the current running system is not provided.

The basePath parameter is optionally used to set the base path for translations. If this option is not set, the default path will be assets/flutter_i18n. This path must be the same path as the one defined in your pubspec.yaml.

The forcedLocale parameter is optionally used to force a locale instead finding the system one.

E2EFileTranslationLoader configuration

The same as FileTranslationLoader configuration. This loader can be used for solving problem with flutter drive testing. It removes using separate isolate for loading translations (detailed issue described here: issues/24703).

The useE2E parameter:

  • if you are in flutter drive testing mode – must be true
  • if you are in normal mode – must be false, in this case FileTranslationLoader will be used

flutter_i18n in action

After the configuration steps, the only thing to do is invoke the following method:

FlutterI18n.translate(buildContext, "your.key")

Where:

  • buildContext is the BuildContext instance of the widget
  • your.key is the key to translate

Other examples of use:

Force a language to be loaded at run-time:

await FlutterI18n.refresh(buildContext, languageCode, {countryCode});

Plural translations:

FlutterI18n.plural(buildContext, "your.key", pluralValue);

Text widget shorthand:

I18nText("your.key", child: Text(""))
I18nText("your.key", translationParams: {"user": "Flutter lover"})
I18nPlural("clicked.times", 1)
I18nPlural("clicked.times", 2, child: Text(""))

If you need to listen the translation loading status, you can use:

  • FlutterI18n.retrieveLoadingStream method, that allows you to listen to every status change
  • FlutterI18n.retrieveLoadedStream method, that allows you to listen when the translation is loaded

For more informations and details, read the CHANGELOG.md.

Utilities

Using flutter pub run flutter_i18n inside the root of your project you can enjoy some utilities that will help you with the translations files management.

Commands

Validate

This command is used to validate all the translations files inside the project.

> flutter pub run flutter_i18n validate
[flutter_i18n DEBUG]: I've found assets/i18n/en.yaml
[flutter_i18n DEBUG]: I've found assets/i18n/it.json
[flutter_i18n DEBUG]: I've found assets/i18n/es.xml
[flutter_i18n DEBUG]: I've found assets/i18n_namespace/en/common.json
[flutter_i18n DEBUG]: I've found assets/i18n_namespace/en/home.yaml
[flutter_i18n DEBUG]: I've found assets/i18n_namespace/ua/common.json
[flutter_i18n DEBUG]: I've found assets/i18n_namespace/ua/home.json
[flutter_i18n INFO]: YAML file loaded for en
[flutter_i18n INFO]: Valid file: assets/i18n/en.yaml
[flutter_i18n INFO]: JSON file loaded for it
[flutter_i18n INFO]: Valid file: assets/i18n/it.json
[flutter_i18n INFO]: XML file loaded for es
[flutter_i18n INFO]: Valid file: assets/i18n/es.xml
[flutter_i18n INFO]: JSON file loaded for common
[flutter_i18n INFO]: Valid file: assets/i18n_namespace/en/common.json
[flutter_i18n INFO]: YAML file loaded for home
[flutter_i18n INFO]: Valid file: assets/i18n_namespace/en/home.yaml
[flutter_i18n INFO]: JSON file loaded for common
[flutter_i18n INFO]: Valid file: assets/i18n_namespace/ua/common.json
[flutter_i18n INFO]: JSON file loaded for home
[flutter_i18n INFO]: Valid file: assets/i18n_namespace/ua/home.json

Diff

This command is used to find the differences between the keys of the desired translation files.

> flutter pub run flutter_i18n diff en.yaml it.json
[flutter_i18n INFO]: [en.yaml, it.json]
[flutter_i18n INFO]: YAML file loaded for en
[flutter_i18n INFO]: JSON file loaded for it
[flutter_i18n ERROR]: The compared dictionary doesn't contain the key >title

Plugins

Plugin Description
flutter_i18n_locize Easy integration locize.io to flutter_i18n.

Do you like my work?

patreon or buy-me-a-coffee

Contributors

Thanks goes to these wonderful people (emoji key):


Anton

🚇 ⚠️ 💻

Lucas Vienna

💻

jlcool

💻

Julian

💻 🤔

Andrey Gordeev

💻 🐛

Amir Panahandeh

🐛 💻

This project follows the all-contributors specification. Contributions of any kind welcome!

More Repositories

1

docker-surfshark

Docker container with OpenVPN client preconfigured for SurfShark
Shell
131
star
2

docker_buildx

GitHub actions with docker buildx
JavaScript
23
star
3

tele_uploader

Telegram bot able to upload large file, also on Dropbox!
PHP
22
star
4

SiteAlert-Python

SiteAlert, what are you waiting for?
Python
22
star
5

native-federation-typescript

Bundler agnostic plugin to share federated types
TypeScript
17
star
6

re-flusso

Utility library to operate with JavaScript Streams API
TypeScript
13
star
7

vscode-remote-tunnels

VSCode remote tunnels Docker image that can be easily deployed everywhere you want
Dockerfile
9
star
8

bluetooth_piconet

Create bluetooth piconet in Android with this simple application!
Java
6
star
9

elements-impaginator

Project used to generate the page configuration of your web components using the `microlc-element-composer` standard
TypeScript
6
star
10

seqproto-schemify

Generate seqproto code from json schema
TypeScript
4
star
11

italian_free_iptv

Script that will push, everyday, free iptv channels on gists
Java
4
star
12

Viope2014

Java
2
star
13

dhcp_dos

DHCP Denial Of Service tool
Python
2
star
14

sesamo-backend

Backend API for Sesamo project
TypeScript
2
star
15

xdcc-mule

xdcc-mule port to NodeJS
TypeScript
2
star
16

sharpDash

sharpDash is a C# porting of the famouse JavaScript Lodash library
C#
2
star
17

vscode_settings

Settings repo for vscode
2
star
18

monorepo-vite

Repository used for the talk "Monorepo: come te li aggiusto con un cacciaVite"
2
star
19

nodejs_tutorials

Node.js tutorials
TypeScript
1
star
20

docker-brains

Docker images for Jetbrains products
Dockerfile
1
star
21

rar-on-arm

This Docker image will provide rar binary for arm platforms
Dockerfile
1
star
22

sveltwind

The fastest way to include Tailwind CSS in your Svelte project
JavaScript
1
star
23

ilteoood

1
star
24

napi-rs-benchmark

NAPI-RS benchmark, with different use cases
JavaScript
1
star
25

native-federation-tests

Bundler agnostic plugin to share aggregated files for tests
TypeScript
1
star
26

interceptor-repro

TypeScript
1
star
27

module-federation-typescript

Module federation TypeScript bug repro
1
star