패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.37.1

flutter_i18n

Flutter용 i18n이 간편해졌습니다. flutter_i18n를 사용하면 단순한 .json, .xml, .yaml 또는 .toml 파일만으로 앱을 국제화할 수 있습니다!

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
2.9만
좋아요
204
Pub 점수
140

패키지 설치

flutter pub add flutter_i18n

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

flutter_i18n은 JSON, XML, YAML 또는 TOML과 같은 간단한 구성 파일을 통해 Flutter 앱에서 국제화를 단순화합니다. 복잡한 설정 없이 언어를 동적으로 전환할 수 있어 글로벌 사용자를 대상으로 하는 앱에 적합합니다. 이 패키지는 Flutter의 위젯 트리와 원활하게 통합되며, 번역이 누락되었을 경우의 백업 메커니즘도 지원합니다. 최소한의 반복 코드로 여러 플랫폼에서 로컬라이제이션 워크플로우를 간편하게 만듭니다.

사용 사례

  • 다국어 앱 지원
  • 동적 언어 전환
  • 간단한 번역 파일 통합
  • 크로스 플랫폼 로컬라이제이션
  • 백업 번역 처리
  • 새로운 개발자를 위한 쉬운 온보딩

주요 기능

  • 다양한 파일 형식 (JSON, YAML, XML, TOML)을 지원합니다
  • 자동 로케일 감지
  • 동적 언어 전환
  • 백업 언어 지원
  • 최소한의 설정 필요
  • 내장 번역 도우미

적합한 대상

  • 국제 사용자를 대상으로 하는 앱
  • i18n 초보 개발자
  • 자주 언어가 업데이트되는 프로젝트
  • 크로스 플랫폼 애플리케이션
  • 외부 번역 워크플로우를 사용하는 팀

고려 사항

  • 수동 번역 파일 관리가 필요합니다
  • 제한된 내장 번역 편집 도구
  • 번역 서비스와 실시간 동기화 없음
  • 파일 형식의 일관성은 필수적입니다
  • 대규모 기업 번역 시스템에 적합하지 않음

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

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.

Translation files are resolved automatically from most to least specific locale. Given a device locale of zh_Hans_CN, the loader tries each of the following in order, using the first file it finds:

  1. zh_Hans_CN (language + script + country)
  2. zh_CN (language + country)
  3. zh_Hans (language + script)
  4. zh (language only)
  5. The fallbackFile (e.g. en)

No configuration is needed — just provide files for the locales you support and the loader will pick the best match automatically.

The fallbackFile parameter provides a default language used when no translation file matches the current locale. This should contain the name of a valid translation file in the assets folder. Keys missing from the matched locale file are filled in from the fallback.

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.

Translation files are resolved using the same priority as FileTranslationLoader (most specific locale to least specific), with the final fallback to fallbackFile.

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:

MaterialApp(
  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:

MaterialApp(
  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 locale directory is resolved using the most specific locale available (e.g. zh_Hans_CN, then zh_CN, then zh_Hans, then zh). If none of those directories contain the requested namespace file, the loader falls back to fallbackDir.

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
Unused

This command is used to find out the unused translation assets in your project.

Some flag for the command:

  • --md: to generate Markdown report file.
  • --path=<path>: to determine where the report file is stored (default is unused_translations.md).
  • --scan=<file/dir>: to determine the files scanned (default is /lib and /test).
> flutter pub run flutter_i18n unused
=== Unused translation keys ===
Defined in translation files but never referenced in source code
Total: 0

  None

=== Missing translation keys ===
Referenced in source code but not found in translation files
Total: 5

  - args.content
  - args.title
  - button.label.clickMea
  - home.missing
  - type

=== Dynamic keys ===
Keys constructed with variables or expressions — cannot analyze statically
Total: 0

  None

Plugins

Plugin Description
flutter_i18n_locize Easy integration locize.io to flutter_i18n.

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!

카테고리

의존성

의존성 목록 9 개

소스 저장소

이 패키지를 사용하는 프로젝트