パッケージ、リポジトリ、アプリカテゴリを検索

GitHub リポジトリmsayed-cs/localize_and_translate

ローカライズして翻訳する

簡単なステップでFlutterのローカライゼーション

ローカライズして翻訳する のプロジェクト画像
スター
50
フォーク
24
最終プッシュ(UTC)
2025/01/01
プロジェクト状態
公開中

元の README

以下は英語原文のスナップショットです。最新版は GitHub をご覧ください。

localize_and_translate

Flutter localization in easy steps, eas

License Pub Example

PUB GitHub stars GitHub forks

Getting Started

🔩 Installation

Add to your pubspec.yaml:

dependencies:
  localize_and_translate: <last_version>

Create folder and add translation files like this

assets
└── lang
    ├── {languageCode}.{ext}                  //only language code
    └── {languageCode}-{countryCode}.{ext}    //or full locale code

Example:

assets
└── lang
    ├── en.json
    └── en-US.json 

Declare your assets localization directory in pubspec.yaml:

flutter:
  assets:
    - assets/lang/
⚠️ 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>
⚙️ Configuration

Add LocalizedApp widget like in example

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
    await LocalizeAndTranslate.init(
        assetLoader: const AssetLoaderRootBundleJson('assets/lang/'), // <-- change the path of the translation files
        supportedLanguageCodes: <String>['ar', 'en'], // <-- or supportedLocales: [Locale('ar', 'EG'), Locale('en', 'US')],
    );
  
    runApp(
        LocalizedApp(
            child: MaterialApp(
              // style 1
              builder: LocalizeAndTranslate.directionBuilder,
              // style 2
              builder: (BuildContext context, Widget? child) {
                child = LocalizeAndTranslate.directionBuilder(context, child);
        
                return child;
              },
              home: const MyHomePage(),
              locale: context.locale,
              localizationsDelegates: context.delegates,
              supportedLocales: context.supportedLocales,
            ),
        ),
    );
}

Full example

📜 Localize And Translate init properties
Properties Required Description
supportedLanguageCodes or next List of supported languages to be converted to locales.
supportedLocales or prev List of supported locales.
assetLoader true Class loader for localization values. You can create your own class.
assetLoadersExtra true Class loader for localization values. You can create your own class.
defaultType false Path to your folder with localization files.
mapper false Mapper for localization values. You can create your own class.
hivePath false Path to hive box.
hiveBackendPreference false Hive backend preference.

Usage

Init

Call LocalizeAndTranslate.init(params) in your main before runApp.

void main() async{
  // ...
  // Needs to be called so that we can await for LocalizeAndTranslate.init();
  WidgetsFlutterBinding.ensureInitialized();

  await LocalizeAndTranslate.init(
    assetLoader: const AssetLoaderRootBundleJson('assets/lang/'), // <-- change the path of the translation files
    supportedLocales: <Locale>[Locale('ar', 'EG'), Locale('en', 'US')], // <-- or  supportedLanguageCodes: <String>['ar', 'en'],
    defaultType: LocalizationDefaultType.asDefined, // <-- change the default type
  );
  // ...
  runApp(
    // ...
  );
  // ...
}

or over network

void main() async{
  // ...
  // Needs to be called so that we can await for LocalizeAndTranslate.init();
  WidgetsFlutterBinding.ensureInitialized();

  await LocalizeAndTranslate.init(
    assetLoader: const AssetLoaderNetwork({
      'ar': 'https://raw.githubusercontent.com/msayed-net/localize_and_translate/main/example/assets/lang/ar.json',
      'en': 'https://raw.githubusercontent.com/msayed-net/localize_and_translate/main/example/assets/lang/en.json',
    }),
    supportedLocales: <Locale>[Locale('ar', 'EG'), Locale('en', 'US')],
    defaultType: LocalizationDefaultType.asDefined,
  );
  // ...
  runApp(
    // ...
  );
  // ...
}
context extensions

LocalizeAndTranslate uses extension methods [BuildContext] for access to some values.

Example:

// set locale
context.setLocale(Locale('en', 'US'));

// set language code
context.setLanguageCode('en');

// get locale
context.locale; // en_US

// get language code
context.languageCode; // en
Translate tr()

Main function for translate your language keys

print('title'.tr(defaultValue: 'Awesome App')); //String
Translations

as json values pair

{
  "title": "Awesome App",
  "hello": "Hello",
  "world": "World!",
}
API Reference
Properties Extension Type Description
countryCode context Property Gets the country code of the current locale.
delegates context Property Gets the list of localization delegates used for translation.
init no Method Initializes the plugin with the desired configuration values.
locale context Property Gets the current locale being used for localization.
resetLocale context Method Resets the current locale to its default value.
setLanguageCode context Method Sets the language code for localization.
setLocale context Method Sets the current locale to one of the supported locales.
supportedLocales context Property Gets the list of supported locales for the app.
getKeys context Method Retrieves the list of keys for the current localization file.
tr string Method Retrieves the translated string for a given localization key.

Reset everything to default values passed through init().

Example:

RaisedButton(
  onPressed: (){
    context.resetLocale();
  },
  child: Text(LocaleKeys.reset_locale).tr(),
)
Mohamed Sayed GitHub avatar
GitHub 作者

Mohamed Sayed ↗

AI Lead | MSc Data Science | Platform Engineer 🚀

言語DartCMakeRubyC++SwiftCHTMLShellKotlinObjective-C

カテゴリー

使用している依存関係

依存関係一覧 7 件

  • flutter{"sdk":"flutter"}
  • flutter_localizations{"sdk":"flutter"}
  • hive^2.2.3
  • hive_flutter^1.1.0
  • dio^5.7.0
  • flutter_test開発用{"sdk":"flutter"}
  • flutter_lints開発用^2.0.1

プロジェクトに合うリポジトリを選ぶには?

用途で絞り込み、開発状況を比較し、採用前に元のリポジトリで要件を確認しましょう。

  1. 名前・作者・説明で検索し、技術トピックで絞り込みます。
  2. スター、フォーク、最近のプッシュを比較します。スターは関心の目安であり、品質の保証ではありません。
  3. 利用前に GitHub で README、ライセンス、Issues を確認します。

情報源と管理

“A repository is the most basic element of GitHub.”

GitHub Docs — About repositories ↗