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

패키지 상세v1.0.0

flutter_localization

Flutter Localization는 맵 데이터를 사용한 앱 내 로컬라이제이션을 위한 패키지입니다. flutter_localizations 자체에서 영감을 받아 더 쉽게, 빠르게 구현할 수 있습니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
10.9만
좋아요
474
Pub 점수
160

패키지 설치

flutter pub add flutter_localization

패키지 개요

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

Flutter Localization는 맵 기반 데이터를 사용하여 앱 내 로컬라이제이션을 단순화하기 위해 설계된 패키지입니다. 국제화 구현을 간소화하여 Flutter 앱 내 번역 관리를 더 빠르고 쉽게 만듭니다. 공식 flutter_localizations 패키지에서 영감을 받았으며, 여러 언어와 플랫폼을 지원하여 Android, iOS, Web, macOS, Windows, Linux에서 효율적으로 다국어 경험을 제공할 수 있게 해줍니다.

사용 사례

  • 다국어 앱 지원
  • 간편한 번역 관리
  • 앱 내 언어 전환
  • 크로스 플랫폼 로컬라이제이션
  • 빠른 i18n 통합
  • 동적 언어 업데이트

주요 기능

  • 지도 기반 번역 저장소
  • 경량이고 빠른 설정
  • flutter_localizations에서 영감을 받아
  • 모든 주요 플랫폼을 지원합니다
  • 언어 처리를 위한 간단한 API
  • 내장된 백업 메커니즘

적합한 대상

  • 다국어 앱을 개발하는 개발자
  • 빠른 i18n 구현이 필요한 팀
  • 동적 언어 변경이 필요한 프로젝트
  • 글로벌 청중을 대상으로 하는 앱
  • 빠른 배포에 집중하는 스타트업
  • 번역을 관리하는 프론트엔드 팀

고려 사항

  • 수동 맵 데이터 설정이 필요합니다
  • 제한된 내장 번역 도구
  • 외부 소스와 실시간 동기화 없음
  • 정적 또는 반정적 콘텐츠에 가장 적합
  • 대규모 번역 워크플로우를 위해 추가 도구가 필요할 수 있습니다
  • 즉시 사용 가능한 완전한 i18n 솔루션이 아님

원본 README

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

Flutter Localization

Flutter Localization is a package used for in-app localization with Map data or JSON assets. It is designed to be easy and fast to implement. This package is inspired by the Flutter SDK flutter_localizations itself. Follow the steps below to use the package, or you can check out a small example project of the package.

Buy Me a Coffee Buy Me a Coffee at ko-fi.com

Breaking Changes

  • From version 0.3.0 onward, there is a major update that breaks the code in the initialize flow. Please re-check the Project Configuration section to see more detail of migration from version 0.2 to 0.3. Don't worry, there are only a few things to change and add.

How To Use

Prepare Language Source

From version 0.4.0 onward, we support 2 ways of language source (in-memory Map data and JSON asset file).

  • In-memory Map data: use more RAM but faster load time. Recommend for 3-5 languages support base on amount of content you have in each Map data.
  • JSON Asset file: use less RAM but slightly slower than in-memory Map data. Recommend for more than 5 languages support with large amount of content.
In-memory Map Data (Map<String, dynamic>)

Create a dart file which will contain all the Map data of the locale language your app need. You can change the file name, class name, and file path whatever you like. Example:

mixin AppLocale {
  static const String title = 'title';

  static const Map<String, dynamic> EN = {title: 'Localization'};
  static const Map<String, dynamic> KM = {title: 'ការធ្វើមូលដ្ឋានីយកម្ម'};
  static const Map<String, dynamic> JA = {title: 'ローカリゼーション'};
}
Asset File (JSON assets)

You can also store your translations in JSON files and load them via assets. Asset's path is not restricted but the file name is. You need to name the file follow your supported language code. For example, create assets/i18n/en.json:

{
  "title": "Localization"
}

Then declare the assets in your pubspec.yaml:

flutter:
  assets:
    - assets/i18n/en.json
    - assets/i18n/km.json
    - assets/i18n/ja.json

Project Configuration

  • Ensure plugin initialize. Update main function into async function, add WidgetsFlutterBinding.ensureInitialized() and await FlutterLocalization.instance.ensureInitialized() before runApp() function like below.
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterLocalization.instance.ensureInitialized();
  runApp(const MyApp());
}
  • Initialize the FlutterLocalization object (this can be local or global, up to you)

final FlutterLocalization localization = FlutterLocalization.instance;
  • Provide the list of MapLocale or JsonLocale and startup language for the app. This has to be done only at the main.dart or the MaterialApp in your project.
@override
void initState() {
  super.initState();
  localization.onTranslatedLanguage = _onTranslatedLanguage;
  // Initialize with map-based
  _initializeLocalizationMapBased();
  // or JSON asset base on your language source 
  _initializeLocalizationJsonAsset();
  // make sure to use only 1 type of source
}

// The setState call here is required to rebuild the app after language changes.
void _onTranslatedLanguage(Locale? locale) {
  setState(() {});
}

void _initializeLocalizationMapBased() {
  localization.init(
    initLanguageCode: 'en',
    source: LocalizationSource.map,
    mapLocales: const [
      MapLocale('en', AppLocale.EN),
      MapLocale('km', AppLocale.KM),
      MapLocale('ja', AppLocale.JA),
    ],
  );
}

void _initializeLocalizationJsonAsset() {
  localization.init(
    initLanguageCode: 'en',
    source: LocalizationSource.jsonAsset,
    jsonLocales: const [
      JsonLocale('en', 'assets/i18n/en.json'),
      JsonLocale('km', 'assets/i18n/km.json'),
      JsonLocale('ja', 'assets/i18n/ja.json'),
    ],
  );
}
  • Add supportedLocales and localizationsDelegates to the MaterialApp
@override
Widget build(BuildContext context) {
  return MaterialApp(
    supportedLocales: localization.supportedLocales,
    localizationsDelegates: localization.localizationsDelegates,
    home: const SettingsScreen(),
  );
}
  • Call the translate() function anytime you want to translate the app and provide it with the language code
ElevatedButton(
  child: const Text('English'),
  onPressed: () {
    localization.translate('en');
  },
);
  • To display the value from the Map data, just use the getString() extension by providing the context (the AppLocale.title is the constant from mixin class above)
AppLocale.title.getString(context);

Extras

  • You also can get the language name too. If you don't specify the language code for the function, it will return the language name depend on the current app locale
localization.getLanguageName(languageCode: 'en');  // English
localization.getLanguageName(languageCode: 'km');  // ភាសាខ្មែរ
localization.getLanguageName(languageCode: 'ja');  // 日本語

localization.getLanguageName();  // get language name depend on current app locale
  • If you need to use locale identifier in some case, you can get it from the current locale. The identifier format is languageCode_scriptCode_countryCode. For scriptCode and countryCode are optional, this might return only the languageCode.
localization.currentLocale.localeIdentifier;

Some Update Note

Version 0.4.0
  • Added support for loading translations from JSON assets using the new JsonLocale model.
  • Introduced LocalizationSource enum to choose between LocalizationSource.map and LocalizationSource.jsonAsset.
Version 0.3.0

From version 0.3.0 onward, there is a major update that breaks the code in the initialize flow. Please re-check the README document at the beginning of the Project Configuration section to see more. The breaking change is related to:

  • Update main() function from void to Future<void> async for package ensureInitialized function
  • Call ensureInitialized() function to init the core functionality of the package
Version 0.1.13

Added Strings Util and Context Extension for helping with localization text that are dynamic base on language. Check the usage below or the example here.

  • As for Strings Util, it just formats string normally from the list of arguments to the full text string.
Strings.format('Hello %a, this is me %a.', ['Dara', 'Sopheak']);
// Result: Hello Dara, this is me Sopheak.
  • As for Context Extension, the full text and arguments you provide, will use to check and get data from the string source. If the result is null, it will return the key that use to get the resource string.
context.formatString('This is %a package, version %a.', [AppLocale.title, 'LATEST'])
// Result: This is Localization package, version LATEST.
Version 0.1.11

You can provide the font family in the MapLocale model at the init() function that can be from Assets or GoogleFonts package.

// font family from asset
MapLocale('en', AppLocale.EN, fontFamily: 'MuseoSans');

// or from GoogleFonts package
MapLocale('en', AppLocale.EN, fontFamily: GoogleFonts.lato().fontFamily);

Lastly, provide the font family to the MaterialApp's ThemeData

@override
Widget build(BuildContext context) {
    return MaterialApp(
        supportedLocales: localization.supportedLocales,
        localizationsDelegates: localization.localizationsDelegates,
        home: const SettingsScreen(),
        theme: ThemeData(fontFamily: localization.fontFamily),
    );
}

카테고리

의존성

의존성 목록 1 개

소스 저장소

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