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

패키지 상세v2.0.0

localization_plus

Dart 기반 앱을 위한 간편하고 고급이며 빠른 국제화

AndroidiOSmacOSWindowsLinux
30일 다운로드
16
좋아요
3
Pub 점수
140

패키지 설치

flutter pub add localization_plus

패키지 개요

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

Localization_plus는 Dart 및 Flutter 애플리케이션에 국제화(i18n)를 추가하기 위한 가볍고 고성능 패키지입니다. 복수형, 성별, 복잡한 메시지 형식 지정을 지원하며 다국어 관리를 쉽게 가능하게 합니다. 간단함과 고급 사용 사례 모두를 고려하여 설계되었으며, Android, iOS, macOS, Windows, Linux 플랫폼에서 빠른 런타임 성능과 원활한 통합을 제공합니다. JSON 기반 번역 파일을 지원하고 동적 언어 전환 및 백업 메커니즘을 위한 깔끔한 API를 제공합니다.

사용 사례

  • 다국어 앱 지원
  • 동적 언어 전환
  • 복수 번역
  • 백업 언어 처리
  • 크로스 플랫폼 로컬라이제이션

주요 기능

  • 빠른 런타임 성능
  • 복수 및 성별 규칙 지원
  • JSON 기반 번역 파일
  • Flutter와의 간편한 통합
  • 자동 로케일 감지

적합한 대상

  • i18n가 필요한 플러터 앱
  • 간단하지만 강력한 로컬라이제이션을 필요로 하는 개발자
  • 여러 지역을 대상으로 하는 프로젝트
  • 자주 언어가 업데이트되는 앱
  • 번역 관리에 JSON을 사용하는 팀

고려 사항

  • 번역 파일의 수동 설정이 필요합니다
  • 번역 워크플로우를 위한 제한된 내장 도구
  • 번역 편집을 위한 내장된 사용자 인터페이스 없음
  • 구조화된 번역 프로세스를 가진 프로젝트에 가장 적합
  • 복잡한 형식을 위해 추가 구성이 필요할 수 있습니다

원본 README

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

Easy, Advanced and Fast Internationalization for your Flutter Apps

platform platform pub package license

About this library

  • ✅ Fully tested code (100% code coverage)
  • 🌐 Easy translations for many languages
  • 🛡️ Null safety
  • 📂 Load translations from JSON file
  • 🧩 Extension methods on BuildContext, String and Text, Enum
  • 🚀 Supports plural, nesting, choice, RTL locales and more
  • ↩️ Fallback locale keys redirection (Optional)
  • 💾 Persistent locale storage (Optional)
  • ❗ Error widget for missing translations
  • 🎧 Listening to localization changes via controller
  • 🔁 Context independent locale change via controller
  • 🌐 Enum translations

Installation

Add to your pubspec.yaml:

dependencies:
  localization_plus: <last_version>

Create folder and add translation files like this

i18n
    ├── {languageCode}.{ext}                  // useOnlyLangCode: true
    └── {languageCode}-{countryCode}.{ext}    // useOnlyLangCode: false (default)

Example:

i18n
    ├── en.json
    └── en-US.json 

Declare your assets localization directory in pubspec.yaml:

flutter:
  assets:
    - i18n/
🚨 Note on iOS

For translation to work on iOS you need to add supported locales to ios/Runner/Info.plist as described here.

Example:

<key>CFBundleLocalizations</key>
<array>
	<string>en</string>
	<string>nb</string>
</array>

Documentation

📄 LocalizationPlusController properties
Properties Required Default Description
supportedLocales true List of supported locales.
path true Path to your folder with localization files.
loader false RootBundleAssetLoader() Class loader for localization files. You can create your own class.
saveLocale false true Whether to save on the device after changing the language
useOnlyLangCode false false Trigger for using only language code for reading localization files.

Example:
en.json //useOnlyLangCode: true
en-US.json //useOnlyLangCode: false (default)
useFallbackTranslations false false If a localization key is not found in the locale file, try to use the fallbackLocale file. sets the first supported language as fallback if fallback locale is not set
fallbackLocale false Set the locale to be used as an alternative if a localization key is not found in the locale file
startLocale false If there is no saved language, set the language in which the system will start
📄 LocalizationPlus widget properties
Properties Required Default Description
key false Widget key.
child true Place for your main page widget.
controller true LocalizationPlusController instance .
Replacing Parameters In Translation Strings

If you wish, you may define placeholders in your translation strings. All placeholders must be between curly brackets. For example, you may define a welcome message with a placeholder name:

{
    "welcome": "Welcome, {name}"
}

If your placeholder contains all capital letters, or only has its first letter capitalized, the translated value will be capitalized accordingly:

"welcome": "Welcome, {NAME}" // Welcome, USER
"welcome": "Welcome, {Name}" // Welcome, User

Usage/Examples

import 'package:flutter/material.dart';
import 'package:localization_plus/localization_plus.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // If you wish, you can define it so that it can be accessed 
  // from anywhere in the system with a package such as the getIt library
  LocalizationPlusController controller = await LocalizationPlusController.init(
    path: 'i18n',
  );

  runApp(
    LocalizationPlus(
      controller: controller,
      supportedLocales: [
        'en_US'.toLocale(),
        'ar_DZ'.toLocale(),
        'tr_TR'.toLocale(),
        'ru_RU'.toLocale(),
      ],
      child: const MyApp()
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Localizations
      localizationsDelegates: context.localizationDelegates,
      supportedLocales: context.supportedLocales,
      locale: context.locale,

      home: MyHomePage()
    );
  }
}

Full example

🔥 Change locale

You can change the locale with the help of BuildContext extension method or controller.

// via context
context.setLocale('en_US'.toLocale());

// via controller
controller.setLocale('en_US'.toLocale());
🔥 Reset locale resetLocale()

Reset locale to initial locale. Sets startLocale to startLocale if startLocale is defined, to deviceLocale if not defined

// via context
context.resetLocale()

// via controller
controller.resetLocale();
🔥 Delete saved locale deleteSavedLocale()

Clears a saved locale from local storage

// via context
context.deleteSavedLocale()

// via controller
controller.deleteSavedLocale();
🔥 Get locale currentLocale

Returns the current locale in the application

// via context
context.currentLocale;

// via controller
controller.currentLocale;
🔥 Get device locale deviceLocale

Returns the device locale

// via context
context.deviceLocale

// via controller
controller.deviceLocale
🔥 Get fallback locale fallbackLocale

Returns the fallback locale. Returns null if useFallbackTranslations is false

// via context
context.fallbackLocale

// via controller
controller.fallbackLocale
🔥 Translate trans()

Main function for translate your language keys

You can use extension methods of [String] or [Text] widget, you can also use trans() as a helper function.

Example:

{
  "notations": "Default: {arg}, Capital: {Arg}, Uppercase: {ARG}",
}
'notations'.trans(arguments: {'arg': 'test'}) // String
// Result: Default: test, Capital: Test, Uppercase: TEST


const Text('notations').trans(arguments: {'arg': 'test'}) // Text
// Result: Text instance


trans('notations', arguments: {'arg': 'test'}) // Helper function
// Result: Default: test, Capital: Test, Uppercase: TEST
Positional Arguments args::

You can replace parameters sequentially from a list without specifying a name key inside {}.

Example:

{
  "welcome": "Welcome {} to {}"
}
'welcome'.trans(args: ["John", "Flutter"]) // Welcome John to Flutter
Arguments:
Name Type Description
arguments Map<String, String> Map of localized strings. Replaces the name keys {key_name} according to its name
namedArgs Map<String, String> Alias for arguments. Map of localized strings.
args List<String> List of localized strings. Replaces {} sequentially from left to right.
gender String Gender switcher. Changes the localized string based on gender string mapping.
🔥 Gender Selection

Changes the translated string based on a requested gender output.

Example:

{
  "profile": {
    "male": "He is {}, reading {}",
    "female": "She is {}, reading {}",
    "other": "They are {}, reading {}"
  }
}
'profile'.trans(gender: "female", args: ['Jane', 'a book']) 
// She is Jane, reading a book
🔥 Plurals plural()

Pluralization is a complex problem, as different languages have a variety of complex rules for pluralization; however, Localization Plus can help you translate strings differently based on pluralization rules that you define.

You can use extension methods of [String] or [Text] widget, you can also use plural() as a helper function.

🚨 Key "other" required!

Example:

{
  "clicked": {
    "zero": "Today",
    "one": "Tomorrow",
    "two": "2 days later",
    "few": "A few days later",
    "many": "Weeks later",
    "other": "After a long time"
  }
}
// String
'clicked'.plural(0) // Today
'clicked'.plural(1) // Tomorrow
'clicked'.plural(2) // 2 days late
'clicked'.plural(3) // A few days later (Depends on the language)
'clicked'.plural(11) // Weeks later (Depends on the language)
'clicked'.plural(1250) // After a long time (Depends on the language)

// Text
Text('clicked').plural(0) // Today
Text('clicked').plural(1) // Tomorrow
Text('clicked').plural(2) // 2 days late
Text('clicked').plural(3) // A few days later (Depends on the language)
Text('clicked').plural(11) // Weeks later (Depends on the language)
Text('clicked').plural(1250) // After a long time (Depends on the language)

plural('clicked', 0) // Today
plural('clicked', 1) // Tomorrow
plural('clicked', 2) // 2 days late
plural('clicked', 3) // A few days later (Depends on the language)
plural('clicked', 11) // Weeks later (Depends on the language)
plural('clicked', 1250) // After a long time (Depends on the language)

// With Number format
'clicked'.plural(1000000, format: NumberFormat.compact(locale: 'en')) // 1M days later
Arguments:
Name Type Description
arguments Map<String, String> Map of localized strings. Replaces the name keys {key_name} according to its name
namedArgs Map<String, String> Alias for arguments. Map of localized strings.
args List<String> List of localized strings. Replaces {} sequentially from left to right.
name String Name of the number formatted into the output string ({$name}).
format NumberFormat Use NumberFormat to parse and format injected numbers automatically.
🔥 Trans Choice transChoice()

You may create more complex pluralization rules which specify translation strings for multiple ranges of values.

You can use extension methods of [String] or [Text] widget, you can also use transChoice() as a helper function.

Example:

{
  "price": {
    "0": "Free",
    "1:5": "Cheap",
    "6:10": "Normal",
    "*": "Expensive"
  }
}
// String
'price'.transChoice(0) // Free
'price'.transChoice(1) // Cheap
'price'.transChoice(3) // Cheap
'price'.transChoice(6) // Normal
'price'.transChoice(10) // Normal
'price'.transChoice(1250) // Expensive

// Text
('price').transChoice(0) // Free
('price').transChoice(1) // Cheap
('price').transChoice(3) // Cheap
('price').transChoice(6) // Normal
('price').transChoice(10) // Normal
('price').transChoice(1250) // Expensive

transChoice('price', 0) // Free
transChoice('price', 1) // Cheap
transChoice('price', 3) // Cheap
transChoice('price', 6) // Normal
transChoice('price', 10) // Normal
transChoice('price', 1250) // Expensive
Arguments:
Name Type Description
arguments Map<String, String> Map of localized strings. Replaces the name keys {key_name} according to its name
🔥 Listening for locale change

You can listen to locale changes with the help of the controller.

controller.addListener(() {
  // Locale changed
  // Refetch language dependent remote data etc.
});
🔥 Linked translations:

If there's a translation key that will always have the same concrete text as another one you can just link to it. To link to another translation key, all you have to do is to prefix its contents with an @: sign followed by the full name of the translation key including the namespace you want to link to.

{
  "hello": "Hello",
  "world": "World",
  "hello_world": "@:hello @:world"
}

You can also do nested anonymous and named arguments inside the linked messages.

Formatting linked translations:

If the language distinguishes cases of character, you may need to control the case of the linked locale messages. Linked messages can be formatted with modifier @.modifier:key

The below modifiers are available currently.

  • upper: Uppercase all characters in the linked message.
  • lower: Lowercase all characters in the linked message.
  • capitalize: Capitalize the first character in the linked message.

xample:

{
  ...
  "hello": "Hello",
  "world": "World",
  "hello_world": "@.upper:hello @.lower:world" // HELLO world
  ...
}
🔥 Check translation exists transExists()

You can check if a key has a translation

'notations'.transExists() // String
// Result: true

transExists('not_exists') // Helper function
// Result: false

🧩 Extensions

String Extension
'en_US'.toLocale(); // Locale('en', 'US')

//with custom separator
'en|US'.toLocale(separator: '|') // Locale('en', 'US')
Enum Extension

You can quickly add translations to your enum values.

{
  "enums": {
    "response_status_type": {
      "successful": "Successful",
      "server_error": "Server Error"
    }
  },
}
ResponseStatusType.successful.description; //Successful
ResponseStatusType.serverError.description; //Server Error
Build Context Extension
context.currentLocale // get current locale

context.deviceLocale // get device locale

context.fallbackLocale // get fallback locale

context.supportedLocales // get supported locales

context.localizationDelegates // get localization delegates

Screenshots

Arabic RTL English LTR Turkish LTR Russian LTR
Arabic RTL English LTR Turkish LTR Russian LTR

카테고리

의존성

의존성 목록 3 개

소스 저장소

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

아직 데이터가 없습니다.