The internationalization i18n library for Flutter

admin

The internationalization (i18n) library for Flutter

flutter_translate

he internationalization (i18n) library for Flutter.

It lets you define translations for your content in different languages and switch between them easily.

Installation

Add this to your package’s pubspec.yaml file:

dependencies:
  flutter_translate: ^1.2.5

Install packages from the command line (or from your editor):

flutter pub get

Configuration

Import flutter_translate:

import 'package:flutter_translate/flutter_translate.dart';

Place the json localization files in a folder of your choice within the project.

By default flutter_translate will search for localization files in the assets/i18n directory in your project’s root.

Declare your assets localization directory in pubspec.yaml

flutter:
  assets:
    - assets/i18n

In the main function create the localization delegate and start the app, wrapping it with LocalizedApp

void main() async
{
  var delegate = await LocalizationDelegate.create(
        fallbackLanguage: 'en',
        supportedLanguages: ['en', 'es_ES', 'fa']);

  runApp(LocalizedApp(delegate, MyApp()));
}

If the assets directory for the localization files is different than the default one (assets/i18n), you need to specify it:

void main() async
{
  var delegate = await LocalizationDelegate.create(
        fallbackLanguage: 'en',
        supportedLanguages: ['en', 'es_ES', 'fa'],
        basePath: 'assets/i18n/');

  runApp(LocalizedApp(delegate, MyApp()));
}

Example MyApp:

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

    var localizationDelegate = LocalizedApp.of(context).delegate;

    return LocalizationProvider(
      state: LocalizationProvider.of(context).state,
      child: MaterialApp(
          title: 'Flutter Translate Demo',
          localizationsDelegates: [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            localizationDelegate
          ],
          supportedLocales: localizationDelegate.configuration.supportedLocales,
          locale: localizationDelegate.currentLocale,
          theme: ThemeData(primarySwatch: Colors.blue),
          home: MyHomePage(),
          ),
    );
  }
}

Usage

Translate a string:

translate('your.localization.key');

Translate with arguments;

translate('your.localization.key', args: {'argName1': argValue1, 'argName2': argValue2});

Translate with pluralization:

translatePlural('plural.demo', yourNumericValue);

JSON:

"plural": {
    "demo": {
        "0": "Please start pushing the 'plus' button.",
        "1": "You have pushed the button one time.",
        "else": "You have pushed the button {{value}} times."
    }
}

Change the language:

@override
Widget build(BuildContext context) {
...
  ...
    changeLanguage(context, 'en');
  ...
...
}

Source Credit Url : https://github.com/bratan/flutter_translate

Leave a Comment