🌎

flutter_localization & intl

2024/10/01に公開

🇺🇸Flutterはデフォルトでは英語らしい

Flutter実践開発の書籍を読んで知った。「えっ日本語で書いてるけど」
なので設定が必要。以下のパッケージを追加せよ

https://pub.dev/packages/intl/install
https://pub.dev/packages/flutter_localization/example

example

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  
  Widget build(BuildContext context) {
    return MaterialApp(
      onGenerateTitle: (context) => AppLocalizations.of(context).title,
      localizationsDelegates: const [
        AppLocalizationsDelegate(),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('en', 'US'),
        Locale('ja', 'JP'),
      ],
      home: const SettingsScreen(),
    );
  }
}

class SettingsScreen extends StatelessWidget {
  const SettingsScreen({super.key});

  
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    return Scaffold(
      appBar: AppBar(title: Text(localizations.title)),
      body: Container(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    child: const Text('English'),
                    onPressed: () {
                      // Change language to English
                    },
                  ),
                ),
                const SizedBox(width: 16.0),
                Expanded(
                  child: ElevatedButton(
                    child: const Text('日本語'),
                    onPressed: () {
                      // Change language to Japanese
                    },
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16.0),
            ItemWidget(
              title: 'Current Language',
              content: Intl.getCurrentLocale(),
            ),
            ItemWidget(
              title: 'String Format',
              content: localizations.thisIs('flutter_localization', '1.0.0'),
            ),
          ],
        ),
      ),
    );
  }
}

class ItemWidget extends StatelessWidget {
  const ItemWidget({
    super.key,
    required this.title,
    required this.content,
  });

  final String title;
  final String content;

  
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(child: Text(title)),
          const Text(' : '),
          Expanded(child: Text(content)),
        ],
      ),
    );
  }
}

class AppLocalizations {
  AppLocalizations(this.locale);

  final Locale locale;

  static AppLocalizations of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations)!;
  }

  static final Map<String, Map<String, String>> _localizedValues = {
    'en': {
      'title': 'Localization',
      'thisIs': 'This is %s package, version %s.',
    },
    'ja': {
      'title': 'ローカリゼーション',
      'thisIs': 'これは%sパッケージ、バージョン%sです。',
    },
  };

  String get title {
    return _localizedValues[locale.languageCode]!['title']!;
  }

  String thisIs(String package, String version) {
    return _localizedValues[locale.languageCode]!['thisIs']!
        .replaceFirst('%s', package)
        .replaceFirst('%s', version);
  }
}

class AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
  const AppLocalizationsDelegate();

  
  bool isSupported(Locale locale) => ['en', 'ja'].contains(locale.languageCode);

  
  Future<AppLocalizations> load(Locale locale) async {
    return AppLocalizations(locale);
  }

  
  bool shouldReload(AppLocalizationsDelegate old) => false;
}

でも状態管理したものが欲しい。Riverpodを追加してみる。

package
name: flutter_templeate_firebase
description: "A new Flutter project."
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=3.4.4 <4.0.0'

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.6
  intl: any
  flutter_localization: ^0.2.2 # --sdk=flutterはできなかった
  flutter_hooks: ^0.20.5
  hooks_riverpod: ^2.5.2
  riverpod_annotation: ^2.3.5

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^3.0.0
  riverpod_generator: ^2.4.0
  build_runner: ^2.4.11
  custom_lint: ^0.6.4
  riverpod_lint: ^2.3.10

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

雑ですができるだけStatelessなものにして状態管理をしています。mixinもあまり使ったことないので使ってみたいと思いWidgetのクラスに継承させてみる。

import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart';

part 'main.g.dart';

void main() {
  runApp(const ProviderScope(child: MyApp()));
}


class LocaleNotifier extends _$LocaleNotifier {
  
  Locale build() => const Locale('en', 'US');

  void changeLocale(Locale locale) {
    state = locale;
  }
}

mixin LocalizationMixin {
  String getString(BuildContext context, String key) {
    return AppLocalizations.of(context).getString(key);
  }

  String formatString(BuildContext context, String key, List<String> args) {
    return AppLocalizations.of(context).formatString(key, args);
  }
}

class MyApp extends ConsumerWidget with LocalizationMixin {
  const MyApp({super.key});

  
  Widget build(BuildContext context, WidgetRef ref) {
    final locale = ref.watch(localeNotifierProvider);

    return MaterialApp(
      onGenerateTitle: (context) => getString(context, 'title'),
      localizationsDelegates: const [
        AppLocalizationsDelegate(),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('en', 'US'),
        Locale('ja', 'JP'),
      ],
      locale: locale,
      home: const SettingsScreen(),
    );
  }
}

class SettingsScreen extends ConsumerWidget with LocalizationMixin {
  const SettingsScreen({super.key});

  
  Widget build(BuildContext context, WidgetRef ref) {
    final localeNotifier = ref.read(localeNotifierProvider.notifier);

    return Scaffold(
      appBar: AppBar(title: Text(getString(context, 'title'))),
      body: Container(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    child: const Text('English'),
                    onPressed: () =>
                        localeNotifier.changeLocale(const Locale('en', 'US')),
                  ),
                ),
                const SizedBox(width: 16.0),
                Expanded(
                  child: ElevatedButton(
                    child: const Text('日本語'),
                    onPressed: () =>
                        localeNotifier.changeLocale(const Locale('ja', 'JP')),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16.0),
            ItemWidget(
              title: 'Current Language',
              content: Intl.getCurrentLocale(),
            ),
            ItemWidget(
              title: 'String Format',
              content: formatString(
                  context, 'thisIs', ['flutter_localization', '1.0.0']),
            ),
          ],
        ),
      ),
    );
  }
}

class ItemWidget extends StatelessWidget with LocalizationMixin {
  const ItemWidget({
    super.key,
    required this.title,
    required this.content,
  });

  final String title;
  final String content;

  
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(child: Text(title)),
          const Text(' : '),
          Expanded(child: Text(content)),
        ],
      ),
    );
  }
}

class AppLocalizations {
  AppLocalizations(this.locale);

  final Locale locale;

  static AppLocalizations of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations)!;
  }

  static final Map<String, Map<String, String>> _localizedValues = {
    'en': {
      'title': 'Localization',
      'thisIs': 'This is %s package, version %s.',
    },
    'ja': {
      'title': 'ローカリゼーション',
      'thisIs': 'これは%sパッケージ、バージョン%sです。',
    },
  };

  String getString(String key) {
    return _localizedValues[locale.languageCode]![key]!;
  }

  String formatString(String key, List<String> args) {
    String value = getString(key);
    for (var arg in args) {
      value = value.replaceFirst('%s', arg);
    }
    return value;
  }
}

class AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
  const AppLocalizationsDelegate();

  
  bool isSupported(Locale locale) => ['en', 'ja'].contains(locale.languageCode);

  
  Future<AppLocalizations> load(Locale locale) async {
    return AppLocalizations(locale);
  }

  
  bool shouldReload(AppLocalizationsDelegate old) => false;
}

Lintの警告が気になる人はこの設定追加してください。インポートの波線が消えると思います。

analysis_options.yaml
analyzer:
  errors:
    unused_import: warning
  exclude:
    - "**/*.g.dart"
    - "**/*.freezed.dart"
  
  strong-mode:
    implicit-casts: false
    implicit-dynamic: false

linter:
  rules:
    - always_declare_return_types
    - cancel_subscriptions
    - close_sinks
    - comment_references
    - one_member_abstracts
    - only_throw_errors
    - package_api_docs
    - prefer_single_quotes
    - sort_child_properties_last


感想

設定は複雑ですが日本語対応ができました。しかし仕事となるともっと設定複雑なので良い方法を考えたいですね。ローカルストレージに言語の変更したのを保存するとか。

Discussion