国際化(i18n)
Flutter国際化(i18n)完全ガイド
Section titled “Flutter国際化(i18n)完全ガイド”Flutterアプリを多言語対応させる方法を詳しく解説します。
1. flutter_localizationsの設定
Section titled “1. flutter_localizationsの設定”pubspec.yamlへの追加
Section titled “pubspec.yamlへの追加”dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter intl: ^0.18.0MaterialAppの設定
Section titled “MaterialAppの設定”import 'package:flutter_localizations/flutter_localizations.dart';
MaterialApp( localizationsDelegates: [ GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: [ Locale('ja', 'JP'), Locale('en', 'US'), ], home: MyHomePage(),)2. リソースファイルの作成
Section titled “2. リソースファイルの作成”ARBファイルの作成
Section titled “ARBファイルの作成”{ "@@locale": "ja", "hello": "こんにちは", "@hello": { "description": "挨拶メッセージ" }, "welcome": "ようこそ、{name}さん", "@welcome": { "description": "ウェルカムメッセージ", "placeholders": { "name": { "type": "String" } } }}{ "@@locale": "en", "hello": "Hello", "@hello": { "description": "Greeting message" }, "welcome": "Welcome, {name}", "@welcome": { "description": "Welcome message", "placeholders": { "name": { "type": "String" } } }}pubspec.yamlの設定
Section titled “pubspec.yamlの設定”flutter: generate: true
l10n: arb-dir: lib/l10n template-arb-file: app_en.arb output-localization-file: app_localizations.dartflutter gen-l10n3. 使用例
Section titled “3. 使用例”import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context)!;
return Scaffold( appBar: AppBar(title: Text(l10n.hello)), body: Center( child: Text(l10n.welcome('Flutter')), ), ); }}4. 言語の切り替え
Section titled “4. 言語の切り替え”class LanguageService { static Future<void> setLanguage(Locale locale) async { final prefs = await SharedPreferences.getInstance(); await prefs.setString('language', locale.languageCode); }
static Future<Locale?> getLanguage() async { final prefs = await SharedPreferences.getInstance(); final languageCode = prefs.getString('language'); if (languageCode != null) { return Locale(languageCode); } return null; }}
// MaterialAppで使用MaterialApp( locale: _currentLocale, localizationsDelegates: [...], supportedLocales: [...],)これで、Flutterでの国際化(i18n)の実装方法を理解できるようになりました。