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

패키지 상세v0.11.1

arb_utils

.arb 파일(국제화/현지화/번역을 다루는 데 사용되는 Dart의 선호 방식)과 함께 작업하기 위한 도구 세트

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
1.3만
좋아요
23
Pub 점수
140

패키지 설치

flutter pub add arb_utils

패키지 개요

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

Flutter 애플리케이션에서 .arb 파일을 다루는 작업을 간소화하도록 설계된 유틸리티 모음으로, 국제화 및 로컬라이제이션을 효율적으로 관리할 수 있게 해줍니다. 이 패키지는 arb 파일의 파싱, 검증, 변환을 지원하여 여러 언어 간 번역을 유지하는 것을 더 쉽게 만듭니다. Dart의 i18n 워크플로우와 원활하게 통합되어 번역 파일과 관련된 반복 작업을 자동화함으로써 개발자 생산성을 향상시킵니다. 대규모 다국어 앱을 관리하는 팀에게 특히 유용합니다.

사용 사례

  • Flutter 앱에서 번역 파일 관리
  • ARB 및 기타 형식 간 변환
  • 번역 키 검증
  • 로컬라이제이션 워크플로우 자동화
  • ARB 파일에서 코드 생성

주요 기능

  • ARB 파일 파싱 및 검증을 지원합니다
  • ARB를 JSON 및 기타 형식으로 변환합니다
  • Flutter의 i18n 시스템과 통합
  • 자동화를 위한 명령줄 인터페이스
  • 일관된 키 이름 및 구조를 보장합니다

적합한 대상

  • 로컬라이제이션에 ARB를 사용하는 플러터 개발자
  • 다중 언어 번역을 관리하는 팀
  • i18n용 CI/CD 파이프라인
  • 자동 번역 처리가 필요한 프로젝트

고려 사항

  • ARB 파일 형식에 익숙해야 합니다
  • ARB 기반 워크플로우에 제한됨
  • CI 통합을 위해 추가 설정이 필요할 수 있습니다
  • 완전한 i18n 프레임워크는 아니지만 도구 세트입니다

원본 README

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

arb_utils

Common actions to perform over .arb formatted strings

Usage

A simple usage example:

import 'package:arb_utils/arb_utils.dart';

main() {
  print('Generating .arb for translators...');
  var chkout = 'latestTranslationsProcessedBranch'; // or a49630b726c or HEAD^3 etc
  Process.runSync('git', 'checkout $chkout'.split(' '));
  var mainARBOld = File('lib/l10n/intl_en.arb').readAsStringSync();
  Process.runSync('git', 'checkout master'.split(' '));
  var mainARBNew = File('lib/l10n/intl_en.arb').readAsStringSync();
  File('lib/l10n/new_translations/intl_en.arb')
      .writeAsStringSync(sortARB(processNewKeys(mainARBNew, mainARBOld)));
  print('lib/l10n/new_translations/intl_en.arb generated');
}

Features

Manual language switching helpers

Normally there's the need of providing a way of manually changing the locale on runtime. Here is a super easy way of doing so depending on the state manager you use:
translation on runtime demo
The solution handles the persistance of the user selection for app restarts and so.

Provider/BLoC

Given that BLoC relies on Provider for working this solution will work easily for both state managers:

//make sure this line is written, your IDE may not add it automatically
import 'package:provider/provider.dart';
import 'package:arb_utils/state_managers/l10n_provider.dart';

//prefix your MaterialApp(//... with the following:
ChangeNotifierProvider(
      create: (_) => ProviderL10n(),
      child: Builder(builder: (context) {
        return MaterialApp(
          locale: context.watch<ProviderL10n>().locale,
          supportedLocales: AppLocalizations.supportedLocales,

//now add this widget wherever you want:
import 'package:arb_utils/arb_utils_flutter.dart';

LanguageSelectorDropdown(
  supportedLocales: AppLocalizations.supportedLocales,
  provider: context.read<ProviderL10n>(),
)
MobX/GetX/GetIt/Riverpod/Binder/Redux/etc

Pull Requests are always welcome :-D!

ArbClient

A way of getting your ARB translations dynamically, not hardcoded like S.of(context).key / AppLocalizations.of(context).key. It has been made with the pretension of supporting a way of getting the .arb files from the backend, on demand, but if it suits your use case, it just works. (PR are always welcome)

var arbClient = ArbClient(englishArbString, locale: 'en', onMissingKey: (key) => print('ARB key not found: $key'), exceptionOnMissingKey: kDebugMode, onMissingKeyValue: (key) => 'value of $key');
print(arbClient['hellowWorld']); // Hello World!
arbClient.reloadJson(json.decode(spanishArbString));
print(arbClient['hellowWorld']); // ¡Hola Mundo!
print(arbClient.get('helloName',{'name':'Nico'})); // ¡Hola Nico!
Standalone functions
sortARB

alters the order of every .arb key alphabetically, putting their @key metadata below every one

{
  "@aKey":{
    "description":"simple description"
  },
  "zKey":"a simple key",
  "@zKey":{
    "description":"simple description"
  },
  "aKey":"a simple key",
}

will be converted to:

{
  "aKey":"a simple key",
  "@aKey":{
    "description":"simple description"
  },
  "zKey":"a simple key",
  "@zKey":{
    "description":"simple description"
  }
}

You can also provide a custom sort function.

var arb1 = '''
{
    "clave":"valor",
    "@clave":{
        "description": "Descripcion"
    },
    "key":"value",
    "@key":{
        "description": "Description"
    }
}''';
var sortedArb1 = sortARB(arb1, (a, b) => a[1].compareTo(b[1]));
print(sortedArb1);
/*
{
    "key":"value",
    "@key":{
        "description": "Description"
    },
    "clave":"valor",
    "@clave":{
        "description": "Descripcion"
    }
}
*/

Know that the most common sortings are implemented out of the box with the following parameters

var sorted = sortARB(arbString, caseInsensitive: false, naturalOrdering: false, descendingOrdering: false);
diffARBs

Will generate a .arb formatted string with the keys that doesn't appear in both the provided .arb formatted arguments

var arb1 = '''
{
    "clave":"valor",
    "@clave":{
        "description": "Descripcion"
    },
    "key":"value",
    "@key":{
        "description": "Description"
    }
}''';
var arb2 = '''
{
    "clave":"valor",
    "@clave":{
        "description": "Descripcion"
    },
    "newKey":"new value",
    "@newKey":{
        "description": "new Description"
    }
}''';
var diffed = diffARBs(arb1, arb2);
print(diffed);
/*
{
    "key":"value",
    "@key":{
        "description": "Description"
    },
    "newKey":"new value",
    "@newKey":{
        "description": "new Description"
    }
}
*/
mergeARBs

Will include the latter .arb keys in the former one and output a .arb formatted string with the merged keys, privileging the latter ones

var former = '''{
  "aKey":"a simple key",
  "@aKey":{
    "description":"simple description"
  },
  "bKey":"a simple key",
  "@bKey":{
    "description":"simple description"
  },
  "zKey":"a simple key",
  "@zKey":{
    "description":"simple description"
  }
''';
var latter = '''{
  "aKey":"a MODIFIED simple key",
  "@aKey":{
    "description":"simple description"
  },
  "cKey":"a simple key",
  "@cKey":{
    "description":"simple description"
  },
  "zKey":"a simple key",
  "@zKey":{
    "description":"simple description"
  }
}''';
var merged = mergeARBs(former,latter);
print(merged);
/*
{
  "aKey":"a MODIFIED simple key",
  "@aKey":{
    "description":"simple description"
  },
  "bKey":"a simple key",
  "@bKey":{
    "description":"simple description"
  },
  "cKey":"a simple key",
  "@cKey":{
    "description":"simple description"
  },
  "zKey":"a simple key",
  "@zKey":{
    "description":"simple description"
  }
}
*/
processNewKeys

Compares an .arb formatted string with a previous version of itself and outputs a new .arb formatted string with the new keys found there (also the edited ones)

var oldVersion = '''{
  "aKey":"a simple key",
  "@aKey":{
    "description":"simple description"
  },
  "bKey":"a simple key",
  "@bKey":{
    "description":"simple description"
  },
  "cKey":"a simple key",
  "@cKey":{
    "description":"simple description"
  },
  "zKey":"a simple key",
  "@zKey":{
    "description":"simple description"
  }
}''';
var newVersion = '''{
  "aKey":"a MODIFIED simple key",
  "@aKey":{
    "description":"simple description"
  },
  "bKey":"a simple key",
  "@bKey":{
    "description":"simple description"
  },
  "cKey":"a simple key",
  "@cKey":{
    "description":"simple description"
  },
  "zKey":"a simple key",
  "@zKey":{
    "description":"A MORE ROBUST description"
  }
}''';
var newARB = processNewKeys(newVersion, oldVersion);
print(newARB);
/*
{
  "aKey":"a MODIFIED simple key",
  "@aKey":{
    "description":"simple description"
  },
  "zKey":"a simple key",
  "@zKey":{
    "description":"A MORE ROBUST description"
  }
}
*/

Bin scripts

Please run

dart pub global activate arb_utils

to enable arb_utils as an executable command on your system.

Sort

To easily sort an arb and update original file, use

arb_utils sort <INPUT FILE>

where <INPUT FILE> is a path to the input file.

Also, there are 3 flags for different sorting:

  • Case insensitive (--case-insensitive / -i): Whether to distinguish between lowercase and uppercase while ordering the keys.
  • Natural ordering (--natural-ordering / -n): Whether to take numbers as a single character and order them according to their numeric value (instead of ASCII one).
  • Descending (--descending / -d): Sort in descending order.

For example, to sort with case insensitive and in descending order, use:

arb_utils sort -i -d <INPUT FILE>
Add Entries

To programmatically add new entries to one or more arb files in one go, use

arb_utils add <key> --description '<description>' [locale:value...]

Example:

arb_utils add welcome --description 'Welcome message' en:'Welcome!' es:'¡Bienvenido!'

Or using a JSON template:

arb_utils add --json '{"welcome": "$VAL$", "@welcome": {"description": "Welcome message"}}' en:'Welcome!' es:'¡Bienvenido!'

The command will recursively find all .arb files in the current directory and its subdirectories by default. To specify specific files, use the --files (or -f) flag. New entries are added to the tail of the files by default. Use the --sort (or -s) flag to sort the files after adding. Note: The command will fail if values for all locales present in the .arb files are not provided.

List Keys

To list keys matching a regexp, use

arb_utils keys <regexp>

This will search in all .arb files found recursively by default. You can also specify files with --files flag.

Add Missing Default Metadata

To easily add missing metadata to an arb and update original file, use

arb_utils generate-meta <INPUT FILE>

where <INPUT FILE> is a path to the input file.

Reference

Check this article for understanding more about i18n with .arb in Flutter: https://phrase.com/blog/posts/flutter-localization/

카테고리

의존성

의존성 목록 6 개

소스 저장소

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