Guide for building internationalized Flutter apps
Authors: Hans Muller (@hansmuller), Shi Hao Hong (@shihaohong)
Go Link: flutter.dev/go/i18n-user-guide
Created: April 2020 / Last updated: September 2020
If you find any issues with this document, please file an issue on Github.
Contents
Glossary
Locale – a compact representation of a written language. The Locale class represents locales, for example Locale(‘en’, ‘US’) represents English as it’s written in the United States.
Locale – 言語のコンパクトな表現。Localeクラスは場所を表します。例えば、Locale(‘en’, ‘US’)
は米国における英語を表します。
Localization – the process of adding support for one or more locales to an application. An app supports a locale when the text the app displays is in the corresponding language.
Localization – 1つ以上のロケールのサポートをアプリケーションに追加するプロセス。 アプリが表示するテキストが対応する言語である場合、アプリはロケールをサポートします。
Internationalization – the process setting up an app so that it can be localized.
Internationalization – ローカライズできるようにアプリを設定するプロセス。
Introduction
We will refer to an app’s “user-facing strings” as messages, and refer to its complete list of user facing strings as its message catalog.
アプリの「ユーザー向け文字列」をメッセージと呼び、ユーザー向け文字列の完全なリストをメッセージカタログと呼びます。
A Flutter application is localized by defining a version of its message catalog for each locale that the application supports. The localized value of a message is often referred to as its “translation”.
Flutterアプリケーションは、アプリケーションがサポートするロケールごとにメッセージカタログのバージョンを定義することでローカライズされます。 メッセージのローカライズされた値は、「翻訳」と呼ばれることがよくあります。
Flutter apps define message catalogs with “Application Resource Bundles”: JSON format files with a “.arb” filename extension.
Flutterアプリは、「Application Resource Bundles(ARB)」ファイルでメッセージカタログを定義します。ARBファイルは拡張子が「.arb」のJSON形式のファイルです。
The messages themselves are defined using a subset of a syntax called ICU, which is supported by many organizations and tools, like Google, Apple, IBM, ICU4J (Java), and ICU4C (C, C++).
メッセージ自体は、ICUと呼ばれる構文のサブセットを使用して定義されます。これは、Google、Apple、IBM、ICU4J(Java)、ICU4C(C、C ++)などの多くの組織やツールでサポートされています。
Although this may all sound like a bit much, it’s not complicated in practice. The following file, called “app_en.arb”, defines a message catalog with a single message called helloWorld.
これは少し難しく聞こえるかもしれませんが、実際にはそれほど複雑ではありません。 「app_en.arb」という名の次のファイルは、helloWorldと呼ばれる単一のメッセージを含むメッセージカタログを定義します。
{ "@@locale": "en", "helloWorld": "Hello World!", "@helloWorld": { "description": "The conventional newborn programmer greeting" } }
The first line indicates that the catalog defines localizations of messages for English.
最初の行は、カタログが英語のメッセージのローカリゼーションを定義していることを示しています。
The “helloWorld” line defines the English translation for the app’s helloWorld message, which is “Hello World!”.
「helloWorld」の行は、アプリのhelloWorldメッセージの英語訳である「HelloWorld!」を定義しています。
The JSON object that follows “@helloWorld” contains a description of the message that’s intended to help translators. It also becomes a comment in the method generated for the message.
「@helloWorld」に続くJSONオブジェクトには、翻訳者を支援することを目的としたメッセージの説明が含まれています。 また、メッセージに対して生成されたメソッドのコメントにもなります。
A Flutter application can look up a message’s translation by using the generated AppLocalizations class.
Flutterアプリケーションは、生成されたAppLocalizationsクラスを使用して、メッセージの翻訳を検索できます。
Text(AppLocalizations.of(context).helloWorld)
Here, we’ve created a Text widget that will display a localized version of the helloWorld message.
ここでは、helloWorldメッセージのローカライズされたバージョンを表示するテキストウィジェットを作成しています↑。
The static AppLocalizations.of() method looks up the message catalog for the locale of the current BuildContext, and returns the translation.
AppLocalizations.of()メソッドは、与えられたBuildContextを用いて、ロケールのメッセージカタログを検索します。そして翻訳(文字列)を返します。
Setting up an internationalized application
Create a new Flutter application in a directory of your choice with the `flutter create` command:
`flutter create`コマンドを実行して、新しいFlutterアプリを、あなたの選択したディレクトリに作成しましょう。
(ターミナルでプロジェクトを生成したいディレクトリまでcdコマンドで移動して、下記のコマンドを実行する。)
flutter create <name_of_flutter_app>
The following sections describe the process for setting up an internationalized application in more detail. Here’s a quick outline of the process:
次のセクションでは、国際化対応アプリケーションを設定(set up)するプロセスについて詳しく説明します。 プロセスの概要は次のとおりです。
- Add the i18n dependencies to your app’s pubspec.yaml file.
- Create a new configuration file for localizations called l10n.yaml.
- Create a new “template” message catalog, like lib/l10n/app_en.arb.
- When the application is run, a new class that provides access to the message catalog will be generated automatically. You’ll import this class.
- (optional) Internationalizing iOS applications
- pubspec.yamlファイルに依存関係としてi18nを追加する。
- l10n.yaml(エル10エヌ.ヤムル)ファイルという名前の、設定ファイルを新規作成する。
- lib/l10n/app_en.arbファイルを新規作成します。(新しいメッセージカタログのテンプレートです。)
- アプリケーションを実行すると、メッセージカタログへのアクセスを提供するクラス(が定義されたファイル)が自動的に生成されます。あなたはそのクラスをインポートして使用します。(pub get、あるいはアプリの実行で自動的に生成される。)
- (オプション) iOSアプリを国際化する。
Update the pubspec.yaml file
Update the Flutter project’s pubspec.yaml to include the `flutter_localizations` and `intl` packages. These packages will be used by your Flutter application and by the code that the localizations tool will generate.
Flutterプロジェクトのpubspec.yamlを更新して、 `flutter_localizations`および` intl`パッケージを含めます。 これらのパッケージは、Flutterアプリケーションとローカリゼーションツールが生成するコードによって使用されます。
In your pubspec.yaml, add the following:
pubspec.yamlファイルを下記のようにしてください。
dependencies: flutter: sdk: flutter # Internationalization support. flutter_localizations: sdk: flutter intl: 0.16.1 # the rest of your dependencies flutter: # Adds code generation (synthetic package) support generate: true
Create the l10n.yaml file
In the root directory of your flutter application, create a new `l10n.yaml` file that contains the following:
あなたのFlutterアプリ(プロジェクト)のルートディレクトリで、`l10n.yaml`ファイルを新規作成し、下記のコードを記述してください。
arb-dir: lib/l10n template-arb-file: app_en.arb output-localization-file: app_localizations.dart
The `l10n.yaml`configuration file is used to customize the tool that generates the localization classes your application will import.
この `l10n.yaml` 設定ファイルは、あなたのアプリがインポートする国際化用クラスを生成するツールをカスタマイズするために使用されます。
- `arb-dir` specifies the directory where the tool expects to find input files. This directory will contain “.arb” format message catalogs.
`arb-dir`は、インプットファイルの場所(ディレクトリ)を指定します。このディレクトリは“.arb” formatのメッセージカタログを含みます。
- `template-arb-file` A message catalog that defines all of the messages your application supports as well as metadata for each message. This file must be created in the arb-dir.
`template-arb-file`アプリケーションがサポートするすべてのメッセージと各メッセージのメタデータを定義するメッセージカタログ。 このファイルはarb-dirに作成する必要があります。
- `output-localization-file` defines the main Dart class file that the tool will generate and your application will import. All of the files generated by the tool will be generated in `arb-dir`.
`output-localization-file`は、ツールが生成し、アプリケーションがインポートするメインのDartクラスファイルを定義します。 ツールによって生成されるすべてのファイルは、 `arb-dir`に生成されます。
The l10n.yaml file supports many other configuration options. See the “Configuring the l10n code generator: The l10n.yaml file” below for details.
l10n.yamlファイルは、他の多くの構成オプションをサポートしています。 詳細については、以下の「l10nコードジェネレーターの構成:l10n.yamlファイル」を参照してください。
Create the template ARB file, lib/l10n/app_en.arb
Create the arb-dir directory and template-arb-file specified in the top-level l10n.yaml file.
arb-dirディレクトリを新規作成します。そして、トップレベルのl10n.yamlファイルで指定したtemplate-arb-file(今回の例ではapp_en.arb)を新規作成します。
The template-arb-file is an ARB format message catalog for one, convenient, locale which defines all of the messages that the application supports.
template-arb-fileは、アプリケーションがサポートする、「すべてのメッセージを定義する1つの便利なロケール」のARB形式のメッセージカタログです。
Note: Filenames for all arb files cannot contain underscores other than for describing the locale. The internationalization tool uses underscores to parse out the language, country, and script codes for each arb file.
注:すべてのarbファイルのファイル名に、ロケールの説明以外にアンダースコアを含めることはできません。 国際化ツールは、アンダースコアを使用して、各arbファイルの言語、国、およびスクリプトコードを解析します。
We could start with the same sample English message catalog discussed earlier.
前に説明したのと同じサンプルの英語メッセージカタログから始めることにしましょう。
{ "@@locale": "en", "helloWorld": "Hello World!", "@helloWorld": { "description": "The conventional newborn programmer greeting" } }
The name of each message in the template catalog will become the name of the Dart method that the application will use to retrieve the localized value of that message.
テンプレートカタログ内の各メッセージの名前は、アプリケーションがそのメッセージのローカライズされた値を取得するために使用するDartメソッドの名前になります。
As noted below, message names like “helloWorld” must be valid Dart method names.
以下で説明するように、「helloWorld」などのメッセージ名は有効なDartメソッド名である必要があります。
Integrating the automatically generated localizations class
The final setup step is to import the generated `app_localizations.dart` file and integrate the AppLocalizations class with your Flutter app:
最後のセットアップ手順は、生成された `app_localizations.dart`ファイルをインポートし、AppLocalizationsクラスをFlutterアプリと統合することです。
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; // Add this line. void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( // Add the `localizationsDelegate` and `supportedLocales` lines. // localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: MyHomePage(title: 'Flutter Demo Home Page'), ); } }
Now the application can look up localizations messages using the AppLocalizations class. For example to give the MyHomePage’s AppBar a localized title:
これで、アプリケーションはAppLocalizationsクラスを使用してローカリゼーションメッセージを検索できます。 たとえば、MyHomePageのAppBarにローカライズされたタイトルを付けるには:
class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( // Replace the title line with the following: title: Text(AppLocalizations.of(context).helloWorld), ), // The rest of the widget tree. ); }
The AppLocalizations class itself imports one additional class per supported locale, i.e. one additional class for each message catalog in the output directory.
AppLocalizationsクラス自体は、サポートされているロケールごとに1つの追加クラスをインポートします。つまり、出力ディレクトリのメッセージカタログごとに1つの追加クラスをインポートします。
The automatically generated localizations class, AppLocalizations
The tool that generates the localizations class will execute automatically each time the application is run or restarted as part of the build process.
ローカリゼーションクラスを生成するツールは、ビルドプロセスの一部としてアプリケーションが実行または再起動されるたびに、自動的に実行されます。
By default, the name of this class is AppLocalizations and you’ll find it in `.dart_tool/flutter_gen/gen_l10n/app_localizations.dart`.
デフォルトでは、このクラスの名前はAppLocalizationsであり、このクラスは、 `.dart_tool / flutter_gen / gen_l10n / app_localizations.dart`にあります。
This means that the generated code will not be checked into version source control, which is by design since the code is an artifact that’s only needed when your Flutter app is built.
これは、生成されたコードがバージョンソース管理にチェックインされないことを意味します。これは、コードがFlutterアプリのビルド時にのみ必要なアーティファクトであるため、設計によるものです。
When running the Flutter app, the IDE may present you with a warning indicating that build errors exist in your project.
Flutterアプリを実行すると、IDEはプロジェクトにビルドエラーが存在することを示す警告を表示する場合があります。
This is because the localizations code will need to be generated for the first time (note that the warnings should be about the missing import and AppLocalizations class not existing).
これは、ローカリゼーションコードを初めて生成される必要があるためです(警告は、インポートの欠落とAppLocalizationsクラスが存在しないことに関するものであることに注意してください)。
Proceed to run the Flutter application, which should generate your localizations code.
Flutterアプリケーションの実行を続けると、ローカリゼーションコードが生成されます。
For example, in VSCode, you can run the Flutter app by selecting “Debug Anyway” in the build error dialog that appears.
例えば、VSCodeでは、表示されるビルドエラーダイアログで「Debug Anyway」を選択することで、Flutterアプリを実行することができます。
Starting with the sample template message catalog, upon successfully building the application, you’ll find two files in the output directory:
サンプルのテンプレートメッセージカタログから始めて、アプリケーションを正常にビルドすると、出力ディレクトリに2つのファイルがあります。
`.dart_tool/flutter_gen/gen_l10n/app_localizations_en.dart`, and `.dart_tool/flutter_gen/gen_l10n/app_localizations.dart`.
The AppLocalizations class, defined in app_localizations.dart, dispatches message lookups to the appropriate locale-specific class, based on the locale requested by application.
app_localizations.dartで定義されているAppLocalizationsクラスは、アプリケーションによって要求されたロケールに基づいて、メッセージルックアップを適切なロケール固有のクラスにディスパッチ(発する)します。
At this point there’s just one locale-specific class, and it’s defined in app_localizations_en.dart.
この時点で、ロケール固有のクラスは1つだけであり、それはapp_localizations_en.dartで定義されています。
If these files were not generated, verify that there are no errors in the Flutter app, and review the steps to ensure that everything has been done correctly.
これらのファイルが生成されなかった場合は、Flutterアプリにエラーがないことを確認し、手順を確認してすべてが正しく行われたことを確認します。
Upon running the app, you’ll see “Hello World!” in the application’s AppBar:
アプリを実行すると アプリケーションのAppBar内に「HelloWorld!」と表示されます。
Adding support for a new locale
To add a Spanish message catalog, create a new file, `lib/l10n/app_es.arb`, and add the following:
スペイン語のメッセージカタログを追加するには、新しいファイル `lib / l10n / app_es.arb`を作成し、下記を記入してください。
{ "@@locale": "es", "helloWorld": "Hola Mundo!" }
This file is just like the template message catalog, except that it only contains translations, it does not contain meta information.
このファイルは、翻訳のみが含まれていてメタ情報は含まれていませんが、それ以外はテンプレートメッセージカタログと同じです。
Now, try hot reloading the application. This will generate the `app_strings_es.dart` file, which will contain the Spanish strings that your application will use.
ここで、アプリケーションをホットリロードしてみてください。 これにより、アプリケーションが使用するスペイン語の文字列を含む `app_strings_es.dart`ファイルが生成されます。
Nothing should have changed in your Flutter application (except if your test device’s locale was already set to Spanish).
Flutterアプリケーションでは何も変更されていないはずです(テストデバイスのロケールがすでにスペイン語に設定されている場合を除く)。
In the next section, we’ll go into more detail about how to change the app’s locale in Flutter.
次のセクションでは、Flutterでアプリのロケールを変更する方法について詳しく説明します。
(optional) Internationalizing iOS Flutter Applications
If you’re testing on an iOS device or plan to support iOS devices in your Flutter application, you will need to correctly update the iOS app bundle with a list consistent with the languages listed in AppLocalizations.supportedLocales. If you plan to follow this user guide with an iOS test device, be sure to add “en” and “es” into that list.
iOSデバイスでテストしている場合、またはFlutterアプリケーションでiOSデバイスをサポートする予定の場合は、AppLocalizations.supportedLocalesにリストされている言語と一致するリストでiOSアプリバンドルを正しく更新する必要があります。 iOSテストデバイスでこのユーザーガイドに従うことを計画している場合は、必ず「en」と「es」をそのリストに追加してください。
Running An Internationalized App
After setting up your Flutter application to handle internationalization, you will need to either update the test device’s locale, or use Localizations.override to see the localized messages.
国際化を処理するようにFlutterアプリケーションを設定した後、テストデバイスのロケールを更新するか、Localizations.overrideを使用してローカライズされたメッセージを表示する必要があります。
While updating the test device’s locale is the most common use-case,
テストデバイスのロケールを更新することが最も一般的な使用例ですが、
let’s go ahead and use Localizations.override first to verify that the localized messages appear correctly in the Flutter application,
まず、Localizations.overrideを使用して、ローカライズされたメッセージがFlutterアプリケーションに正しく表示されることを確認しましょう。
Since using Localizations.override only requires a code change to your Flutter application to see results.
Localizations.overrideを使用すると、結果を表示するためにFlutterアプリケーションのコードを変更するだけで済みます。
On the other hand, the steps for changing a test device’s locale may vary by platform.
一方、テストデバイスのロケールを変更する手順は、プラットフォームによって異なる場合があります。
Localizations.override
Localizations.override is a factory constructor for the Localizations widget that allows for (the usually rare) situation where a section of your application needs to be localized to a different locale than the locale configured for your device.
Localizations.overrideは、Localizationsウィジェットのファクトリコンストラクターであり、アプリケーションのセクションをデバイスに構成されているロケールとは異なるロケールにローカライズする必要がある(通常はまれな)状況を可能にします。
Let’s add some code to the body of your Flutter application to observe this behavior:
この動作を観察するために、Flutterアプリケーションの本体にコードを追加してみましょう。
Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(AppLocalizations.of(context).helloWorld), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ // New code Localizations.override( context: context, locale: const Locale('es'), // Using a Builder here to get the correct BuildContext. child: Builder( builder: (BuildContext context) { return Text(AppLocalizations.of(context).helloWorld); } ), ), // ... ], ), ), // ... ); } }
Upon hot-reloading, you will observe that the same call to AppLocalizations.of(context).helloWorld nested in Localizations.override returns the Spanish string, while AppLocalizations.of(context).helloWorld should return the English string if the test device’s locale was set to a non-Spanish one.
ホットリロードすると、Localizations.overrideにネストされたAppLocalizations.of(context).helloWorldの呼び出しがスペイン語の文字列を返すのに対し、AppLocalizations.of(context).helloWorldは、英語の文字列を返すことが確認できます。 (テストデバイスのロケールがスペイン語以外のものに設定されている場合)
Updating the test device’s locale
Since the steps to update a test device’s locale will be different based on the platform you’re working with, we will omit those steps and leave it to you to figure that out based on the test device you’re using.
テストデバイスのロケールを更新する手順は、使用しているプラットフォームによって異なるため、これらの手順は省略し、使用しているテストデバイスに基づいて判断するようにします。
After updating a platform if you change your device’s locale to Spanish, you will see the following:
プラットフォームを更新した後、デバイスのロケールをスペイン語に変更すると、次のように表示されます。
Defining Messages and Message Catalogs
All of the messages for one locale are defined in a single “.arb” file that contains one JSON object. Typically the object’s first name/value pair defines the file’s locale:
1つのロケールのすべてのメッセージは、1つのJSONオブジェクトを含む単一の「.arb」ファイルで定義されます。 通常、オブジェクトの最初の名と値のペアは、ファイルのロケールを定義します。
{ "@@locale": "en", … message definitions }
The filename can also define the catalog’s locale if it ends in an underscore followed by a locale name. For example app_en_US.arb is a message catalog for the “en_US” locale.
ファイル名は、アンダースコアの後にロケール名が続く場合、カタログのロケールを定義することもできます。 たとえば、app_en_US.arbは、「en_US」ロケールのメッセージカタログです。
Typically apps define the locale redundantly, with both the filename suffix and the “@@locale” entry.
通常、アプリは、ファイル名のサフィックスと「@@ locale」エントリの両方を使用して、ロケールを冗長的に定義します。
Each of the app’s messages must have a name that’s unique relative to the message catalog.
アプリの各メッセージは、メッセージカタログに対して一意の名前を付ける必要があります。
The names must be suitable as Dart method names: camel case, beginning with a lowercase letter.
名前はDartメソッド名として適切である必要があります:小文字で始まるキャメルケース。
Each message should be defined by two name value pairs. The first names the message and specifies its translation.
各メッセージは、2つの「名前と値のペア」で定義する必要があります。 最初はメッセージに名前を付け、その翻訳を指定します。
一つ目の「名前と値のペア」は、「メッセージ名」と「翻訳文字列」のペアです。
The second must have the same name as the first with a single ‘@’ prefix.
二つ目の「名前と値のペア」は、「@メッセージ名」と「JSONオブジェクト」のペアです。
Its value is a JSON object that describes the message for the sake of translators and the code generation tool.
JSONオブジェクトは、翻訳とコード生成ツールのための、メッセージの説明を表すオブジェクトです。
{ "@@locale": "en", "helloWorld": "Hello World", "@helloWorld": { "description": "The conventional newborn programmer greeting" } }
「foo」と呼ばれるすべてのメッセージには、コンパニオン「@foo」エントリが含まれる場合があります。
Although the value of @foo can be empty, it’s a good practice to include a description.
@fooの値は空にすることができますが、説明を含めることをお勧めします。
Messages with parameters require some additional @foo properties, as we’ll see below.
以下に示すように、パラメータを含むメッセージには、いくつかの追加の@fooプロパティが必要です。
2021/8/27 : Flutter : Guide for building internationalized Flutter apps の訳パート2へ続く>>
参考
https://docs.google.com/document/d/10e0saTfAv32OZLRmONy866vnaw0I2jwL8zukykpgWBc/edit