iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🇺🇳

How to install fast_i18n in Flutter

に公開

Introduction

fast_i18n is a library for easily implementing internationalization (i18n) in Flutter. A key feature is that, unlike flutter_localizations, it does not require context.

Installation

Add Package

flutter pub add -d fast_i18n build_runner

Create i18n folder

mkdir lib/i18n

Create JSON files

Create JSON files in the lib/i18n folder. The filename format is as follows:

<namespace>_<locale?>.i18n.json

<namespace> can be anything you like. Here, we'll use translations.
<locale> contains the language name. However, for the English file, please omit the <locale>.

In this example, we will support Japanese and English.

lib
├── i18n
│   ├── translations.i18n.json
│   └── translations_ja.i18n.json
└── main.dart
translations.i18n.json
{
  "hello": "hello"
}
translations_ja.i18n.json
{
  "hello": "こんにちは"
}

Generate Dart files

flutter pub run build_runner build --delete-conflicting-outputs

Please run this again whenever you edit the JSON files.

Edit main.dart

main.dart
void main() {
  WidgetsFlutterBinding.ensureInitialized(); // Added
  LocaleSettings.useDeviceLocale(); // Added
  runApp(MyApp());
}

Configuring flutter_localizations

It seems flutter_localizations settings are also required for fast_i18n.

Add flutter_localizations to pubspec.yaml

pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  flutter_localizations: # Added
    sdk: flutter # Added

Edit main.dart

main.dart
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  LocaleSettings.useDeviceLocale();
  runApp(TranslationProvider(child: MyApp()));
}

Edit MaterialApp

main.dart
MaterialApp(
  locale: TranslationProvider.of(context).flutterLocale,
  supportedLocales: LocaleSettings.supportedLocales,
  localizationsDelegates: GlobalMaterialLocalizations.delegates,
  child: YourFirstScreen(),
)

iOS Setup

Individual settings are required to support iOS.
Edit ios/Runner/Info.plist.
Add the following inside the <dict> tag:

ios/Runner/Info.plist
<key>CFBundleLocalizations</key>
<array>
<string>ja</string>
<string>en</string>
</array>

This completes the installation and setup.

Usage

Translation data is retrieved as follows:

import 'package:my_app/i18n/translations.g.dart';

String hello = t.hello;

Reference

GitHubで編集を提案

Discussion