Dart 및 Flutter를 위한 간단하고 효율적인 국제화 솔루션으로, JSON 파일에서 코드 생성을 통해 번역 클래스를 만듭니다. 최소한의 보일러플레이트로 타입 안전하고 자동 완성 가능한 번역을 가능하게 합니다. 이 패키지는 Flutter 프로젝트에 원활하게 통합되며 Android, iOS, Web, macOS, Windows, Linux 등 모든 주요 플랫폼을 지원합니다. IDE 자동 완성과 컴파일 시점 검사 덕분에 빠른 성능과 향상된 개발자 경험을 제공합니다.
사용 사례
다국어 앱 지원
형 안전한 번역 액세스
IDE에서의 자동 완성
효율적인 런타임 성능
Flutter와의 원활한 통합
번역 파일 유지보수가 쉬움
주요 기능
번역 클래스를 위한 코드 생성
형 안전한 번역 액세스
IDE 자동 완성 지원
최소한의 보일러플레이트
다수의 플랫폼을 지원합니다
빠른 런타임 성능
적합한 대상
로컬라이제이션을 필요로 하는 플러터 앱
다중 언어를 관리하는 팀
타입 안전성을 원하는 개발자
개발자 경험을 우선시하는 프로젝트
글로벌 청중을 대상으로 하는 앱
번역에 JSON을 사용하는 프로젝트
고려 사항
코드 생성 단계가 필요합니다
JSON 파일은 올바르게 구조화되어야 합니다
코드 생성을 위한 초기 설정이 필요합니다
JSON 기반 번역 소스에 한정
내장된 백업 메커니즘이 없습니다
로케일 전환의 수동 처리
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
i18n
Simple internationalization package for Dart and Flutter. This package now supports hot reload and
is tested on
latest versions of Flutter.
Overview
Write your messages into YAML files, and let this package generate convenient Dart classes from those files.
class Messages {
const Messages();
ButtonMessages get button => ButtonExampleMessages(this);
UsersMessages get users => UsersExampleMessages(this);
}
class ButtonMessages {
final Messages _parent;
const ButtonMessages(this._parent);
String get save => "Save";
String get load => "Load";
}
class UsersMessages {
final Messages _parent;
const UsersMessages(this._parent);
String get logout => "Logout";
String welcome(String name) => "Hello $name!";
}
... and use them in your code - plain and simple.
Messages m = Messages();
print(m.users.welcome('World'));
// outputs: Hello World!
Package is an extension (custom builder) for build_runner
(Dart standard for source generation) and it can be used with Flutter, AngularDart
or any other type of Dart project.
Motivation and goals
The official Dart/Flutter approach to i18n seems to be ... complicated and kind of ... heavyweight.
I would like my messages to be checked during compile time. Is that message really there?
Key to the localized message shouldn't be just some arbitrary String, it should be a getter method!
And if the message takes some parameters, the method should take those parameters!
I like to bundle messages into thematic groups, the i18n tool should support that and help me with it.
Dart has awesome string interpolation, I want to leverage that!
messages_de.i18n.yaml (_de = German translation)
generic:
ok: OK
done: ERLEDIGT
invoice:
create: Rechnung erstellen
delete: Rechnung löschen
... run the webdev tool, or build_runner directly, and use your messages like this:
Messages m = Messages();
print(m.generic.ok); // output: OK
print(m.generic.done); // output: DONE
m = Messages_de();
print(m.generic.ok); // output: OK
print(m.generic.done); // output: ERLEDIGT
Parameters and pluralization
The implementation is VERY straightforward, which allows you to do all sorts of crazy stuff:
invoice:
create: Create invoice
delete: Delete invoice
help: "Use this function
to generate new invoices and stuff.
Awesome!"
count(int cnt): "You have created $cnt ${_plural(cnt, one:'invoice', many:'invoices')}."
apples:
_apples(int cnt): "${_plural(cnt, one:'apple', many:'apples')}"
count(int cnt): "You have eaten $cnt ${_apples(cnt)}."
Now see the generated classes:
class Messages {
const Messages();
InvoiceMessages get invoice => InvoiceExampleMessages(this);
ApplesMessages get apples => ApplesExampleMessages(this);
}
class InvoiceMessages {
final Messages _parent;
const InvoiceMessages(this._parent);
String get create => "Create invoice";
String get help => "Use this function to generate new invoices and stuff. Awesome!";
String get delete => "Delete invoice";
String count(int cnt) => "You have created $cnt ${_plural(cnt, one:'invoice', many:'invoices')}.";
}
class ApplesMessages {
final Messages _parent;
const ApplesMessages(this._parent);
String _apples(int cnt) => "${_plural(cnt, one:'apple', many:'apples')}";
String count(int cnt) => "You have eaten $cnt ${_apples(cnt)}.";
}
See how you can reuse the pluralization of _apples(int cnt)? (nice!)
There are three functions you can use in your message:
How to decide what translation to use (ExampleMessages_de?, ExampleMessages_hu?) is up to you.
The package simply generates message classes, that's all.
import 'messages.i18n.dart';
import 'messages_de.i18n.dart' as de;
void main() async {
Messages m = Messages();
print(m.apples.count(1));
print(m.apples.count(2));
print(m.apples.count(5));
m = de.Messages_de(); // see? ExampleMessages_cs extends ExampleMessages
print(m.apples.count(1));
print(m.apples.count(2));
print(m.apples.count(5));
}
Where and how to store instances of these message classes -
again, up to you. I would consider ScopedModel for Flutter and registering
messages instance into dependency injection in AngularDart.
But in this case a singleton would be acceptable also.
How to use with Flutter
Create YAML file with your messages, for example:
lib/messages/foo.i18n.yaml
Add build_runner as a dev_dependency and i18n as a dependency to pubspec.yaml:
dependencies:
flutter:
sdk: flutter
i18n: any
...
dev_dependencies:
build_runner: any
flutter_test:
sdk: flutter
Open a terminal and in the root of your Flutter project run:
flutter packages pub run build_runner watch
... and keep it running. Your message classes will appear next to YAML files and will be
rebuilt automatically each time you change the source YAML.
For one-time (re)build of your messages run:
flutter packages pub run build_runner build
Import generated messages and use them:
import 'packages:my_app/messages/foo.i18n.dart'
...
Foo m = Foo();
return Text(m.bar);
...
How to use with AngularDart
You are probably using webdev tool already, so you just need to add i18n
as a dependency and that's all.
Custom pluralization
The package can correctly decide between 'one', 'few', 'many', etc. only for
English and Czech (for now). But you can easily plug your own language,
see example/main.dart
and Czech and English
implementation.
If you implement support for your language, please let me know,
I'll gladly embed it into the package.