0
0

flutterで他言語化を実装してみる

Last updated at Posted at 2024-02-11

そもそもな誤解

他言語化ってapiで吐き出されたデータを翻訳してくれるのではなく、text()内で自分で書いた文言を他言語に置き換えることを知らなかった。

または勝手に翻訳してくれる機能もあるのかもしれないが、今回はそこを深く調べてないので割愛したい。

pubspeck.yamlの設定

dependencies:
flutter:
sdk: flutter
//追加
flutter_localizations:
sdk: flutter
intl: ^0.18.0
// ここまで

もう1箇所
//# The following section is specific to Flutter packages.
flutter:
//追加
generate: true
//ここまで

mainに記載する

return MaterialApp(
//他言語化
localizationsDelegates: [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
Locale('ja', ''), //日本語
Locale('en', ''), //英語
///他の言語の追加も可能
],
home: MyHomePage(),
);

l10nフォルダの作成とその中身

libの中にl10nフォルダを作成。その中にファイルを作成。今回は英語と日本語対応させる
以下にフォルダ階層
lib/l10n/app_en.arb
    app_ja.arb

app_~~.arbファイルの中身は下
{
"@@locale": "en",//英語。日本語の場合は「"@@locale": "ja",」
"hintText": "Enter words e.g., apple, cat",
"key": "「key」と入力すると表示させる文字がこの中に記載されるkeyとvalueの関係",
}

l10n.yamlファイルの作成

pubspeck.ymlと同じフォルダ階層にl10n.yamlファイルを作成。中身は下
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart

使ってみる

//変数で定義 「.hintText」がkeyとなり,valueの値「Enter words e.g., apple, cat」が表示される
String hintText = AppLocalizations.of(context)!.hintText;

TextFormField(
controller: textController,
decoration: InputDecoration(
hintText: hintText,//ヒントテキストが他言語化される。
),
),

エミュレーターのスマホ設定を英語にすると英語・日本語の切り替えができます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0