Internationalizing Flutter apps
How to internationalize your Flutter app.
アプリの開発途中から多言語化対応するとあちこち修正しなければならなくなるので最初から多言語化前提で開発を行います。日本語のみであったとしてもアプリとしては多言語化対応しているけれども日本語のみ設定されている状態が望ましいです。
l10n.yaml
arb-dir: lib/l10n template-arb-file: app_en.arb output-localization-file: app_localizations.dart
pubspec.yaml
dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter intl: ^0.17.0 # intl_translation: 0.17.10+1
intl_translation: 0.17.10+1はintl: ^0.17.0と合わないのでインストールできませんでした。
Internationalizing Flutter apps
How to internationalize your Flutter app.
なので
return MaterialApp( onGenerateTitle: (BuildContext context) => DemoLocalizations.of(context).title,
以降はできません。
lib/my_app.dart
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:my_app_01/my_home_page.dart'; class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } }
lib/my_home_page.dart
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(AppLocalizations.of(context)!.helloWorld), const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
lib/l10n/app_en.arb
{ "helloWorld": "Hello World!", "@helloWorld": { "description": "The conventional newborn programmer greeting" } }
lib/l10n/app_ja.arb
{ "helloWorld": "こんにちは。" }