Skip to content

1. Installation, Configuration & Usage

Florin Bratan edited this page Mar 26, 2024 · 3 revisions

Installation

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

dependencies:
  flutter_translate: <latest version>

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(
        fallbackLocale: 'en_US',
        supportedLocales: ['en_US', '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:

 var delegate = await LocalizationDelegate.create(
      ...
        basePath: 'assets/i18n/'
      ...

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.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": {
       "zero": "Please start pushing the 'plus' button.",
	"one": "You have pushed the button one time.",
	"two": "You have pushed the button two times.",
	"other": "You have pushed the button {{value}} times."
    }
}

Change the language:

@override
Widget build(BuildContext context) {
...
  ...
    changeLocale(context, 'en_US');
  ...
...
}
Clone this wiki locally