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

패키지 상세v1.0.7

translate_gen

Flutter에서 번역을 관리하기 위한 도구: 문자열 추출, 로컬라이제이션 구성 및 설정 파일을 사용하여 텍스트 교체

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
35
좋아요
6
Pub 점수
150

패키지 설치

flutter pub add translate_gen

패키지 개요

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

translate_gen은 번역 가능한 문자열을 추출하고 로컬라이제이션 클래스를 생성하며 구성 파일을 통해 번역을 관리함으로써 로컬라이제이션과 국제화를 간소화하는 Flutter 패키지입니다. Android, iOS, Web, macOS, Windows, Linux 등 여러 플랫폼을 지원합니다. 이 도구는 봉쇄 코드를 자동화하고 번역 파일을 쉽게 업데이트할 수 있도록 하여 다국어 앱을 유지 관리하는 과정을 단순화합니다. 개발자는 구조화된 구성 파일에서 언어 키와 해당 번역을 정의하여 일관성을 보장하고 수동 오류를 줄일 수 있습니다.

사용 사례

  • 다국어 앱 콘텐츠 관리
  • 로컬라이제이션 파일 생성 자동화
  • 번역 워크플로우 간소화
  • 동적 언어 전환 지원
  • CI/CD 파이프라인과의 통합
  • 일관된 번역 구조 유지

주요 기능

  • Dart 코드에서 문자열 추출
  • 자동 생성된 로컬라이제이션 클래스
  • 사용자 정의 가능한 번역 파일
  • 다중 언어 지원
  • 플랫폼에 관계없는 설계
  • 빌드 러너와의 간편한 통합

적합한 대상

  • 로컬라이제이션이 필요한 플러터 프로젝트
  • 대규모 번역 세트를 관리하는 팀
  • i18n 자동화를 찾는 개발자
  • 글로벌 대상 사용자를 위한 앱
  • 구조화된 번역 워크플로를 사용하는 프로젝트

고려 사항

  • 빌드 러너 설정이 필요합니다
  • 올바른 파일 구조에 따라 달라집니다
  • 복잡한 경우에 맞춤 설정이 필요할 수 있습니다
  • 제한된 내장 번역 관리
  • 번역 파일과 버전 관리를 함께 사용할 때 가장 효과적입니다

원본 README

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

translate_gen Package

This package provides tools to assist with translation tasks in Flutter projects, including preparing configuration files, extracting translatable strings, and replacing them based on a configuration. It supports multiple AI translation providers including Gemini and DeepSeek R1.

Installation

Add the following to your pubspec.yaml:

dev_dependencies:
  translate_gen: ^1.0.6

Run flutter pub get to install the package.

Commands

1. Prepare Configuration

The prepare command generates a configuration file (prepare.dart) and an empty replace.json file under the assets/translate_gen directory. You can choose between two configuration types: normal or easy (for easy_localization package).

Command:

flutter pub run translate_gen:prepare

Command with Options:

# For normal translation setup
flutter pub run translate_gen:prepare --type normal

# For easy_localization package setup (default)
flutter pub run translate_gen:prepare --type easy

Output:

  • Creates assets/translate_gen/prepare.dart with the following content:

For Easy Localization (default):

import 'package:translate_gen/src/extract/exception_rules.dart';
import 'package:translate_gen/src/translate/translation_provider.dart';

final translationConfig = ExceptionRules(
  textExceptions: ['import'],
  lineExceptions: ['line_start_to_skip'],
  contentExceptions: ['substring_to_skip'],
  folderExceptions: [''],
  extractFilter: [
    RegExp(r"'[^']*[\u0600-\u06FF][^']*'"),
    RegExp(r'"[^"]*[\u0600-\u06FF][^"]*"')
  ],
  import: [
    "import 'package:easy_localization/easy_localization.dart';",
    "import 'package:$projectName/core/app_strings/locale_keys.dart';"
  ],
  key: "LocaleKeys.{key}.tr()",
  keyWithVariable: "LocaleKeys.{key}.tr(args: [{args}])",
  translate: true,
  extractOutput: 'replace.json',
  aiKey: '', // Required only when using TranslationProvider.gemini
  aiModel: TranslationProvider.deepseekR1, // Available options: gemini, deepseekR1
);

For Normal Translation:

import 'package:translate_gen/src/extract/exception_rules.dart';
import 'package:translate_gen/src/translate/translation_provider.dart';

final translationConfig = ExceptionRules(
  textExceptions: ['import'],
  lineExceptions: ['line_start_to_skip'],
  contentExceptions: ['substring_to_skip'],
  folderExceptions: [''],
  extractFilter: [
    RegExp(r"'[^']*[\u0600-\u06FF][^']*'"),
    RegExp(r'"[^"]*[\u0600-\u06FF][^"]*"')
  ],
  import: [],
  key: "s.current.{key}",
  keyWithVariable: "s.current.{key}({args})", //not work in flutter_localization only in easy_localization
  translate: true,
  extractOutput: 'replace.json',
  aiKey: '', // Required only when using TranslationProvider.gemini
  aiModel: TranslationProvider.deepseekR1, // Available options: gemini, deepseekR1
);
  • Creates assets/translate_gen/replace.json as an empty JSON file:
{}

Purpose:

This command sets up the necessary configuration for the translation process, defining rules for exceptions, filters for extracting translatable strings (e.g., Arabic text), and the format for translation keys.

  • Easy type: Configured for use with the easy_localization package, including the necessary import and .tr() method calls
  • Normal type: Basic configuration without external package dependencies, suitable for custom translation implementations

AI Translation Configuration

The package supports multiple AI translation providers:

Available AI Models
  • TranslationProvider.deepseekR1: DeepSeek R1 model (default)
  • TranslationProvider.gemini: Google Gemini model
Gemini Configuration

When using Google Gemini as your AI model, you must provide a valid API key:

  1. Set the aiModel to TranslationProvider.gemini
  2. Add your Gemini API key to the aiKey field

Example configuration for Gemini:

final translationConfig = ExceptionRules(
  // ... other configuration ...
  aiKey: 'your-gemini-api-key-here',
  aiModel: TranslationProvider.gemini,
);

Note: The aiKey field is only required when using TranslationProvider.gemini and translation is enabled. You can leave it empty when using other AI models.

API Key Sources

2. Extract Translatable Strings

The extract command scans the specified path (or default path) for translatable strings and generates key-value pairs to be stored in replace.json.

Command:

flutter pub run translate_gen:extract [--path='lib/core']

Parameters:

  • --path: Optional. Specifies the directory to scan for translatable strings. Defaults to lib/core if not provided.

Output:

  • Updates assets/translate_gen/replace.json with extracted strings in the format:
{
  "key1": "translatable string 1",
  "key2": "translatable string 2"
}

Purpose: This command identifies strings (e.g., Arabic text matching the regex patterns in prepare.dart) and prepares them for translation by storing them in replace.json. The AI model specified in the configuration will be used for automatic translation.

3. Replace Strings

The replace command replaces strings in the specified path (or default path) with translation keys based on the content of replace.json.

Command:

flutter pub run translate_gen:replace [--path='lib/core']

Parameters:

  • --path: Optional. Specifies the directory where strings will be replaced. Defaults to lib/core if not provided.

Behavior:

  • Reads replace.json to get key-value pairs
  • Replaces matching strings in the specified path with translation keys in the format defined in prepare.dart (e.g., LocaleKeys.{key}.tr() or LocaleKeys.{key}.tr(args: [{args}]) for strings with variables)
  • Adds necessary import statements (e.g., import 'package:easy_localization/easy_localization.dart';) to files as specified in the configuration

Purpose: This command automates the replacement of hard-coded strings with translation keys, enabling easy localization using the easy_localization package.

Directory Structure

After running the prepare command, the following structure is created:

assets/
└── translate_gen/
    ├── prepare.dart
    └── replace.json

Configuration Parameters

ExceptionRules Parameters
Parameter Type Description
textExceptions List<String> Text patterns to exclude from extraction
lineExceptions List<String> Line patterns to skip during extraction
contentExceptions List<String> Content substrings to skip
folderExceptions List<String> Folders to exclude from scanning
extractFilter List<RegExp> Regex patterns to match translatable strings
import List<String> Import statements to add to files
key String Format for translation keys
keyWithVariable String Format for translation keys with variables
translate bool Enable/disable automatic translation
extractOutput String Output file for extracted strings
aiKey String API key for Gemini (required only for Gemini)
aiModel TranslationProvider AI model to use for translation

Notes

  • The extractFilter in prepare.dart is configured to detect Arabic strings (Unicode range \u0600-\u06FF). Modify the regex patterns to support other languages if needed
  • The replace.json file is overwritten during the extract command, so back up any manual changes before running it
  • Before running the replace command, make sure replace.json has the following content (with at least an empty object {})
  • When using Gemini, ensure you have a valid API key from Google AI Studio
  • DeepSeek R1 is the default AI model and doesn't require additional API key configuration
  • The AI translation feature requires an internet connection to communicate with the selected AI provider

카테고리

의존성

의존성 목록 7 개

소스 저장소

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

아직 데이터가 없습니다.