i18n_translator 0.2.2

  • Readme
  • Changelog
  • Example
  • Installing
  • 70

i18n Translator #

pub package

A flutter package designed to make internationalizing your flutter app a breeze. This package simplifies i18n/i10n during development by facilitating modularization and collaboration between team members during the internationalizing process of the app development cycle.

Why #

While there are many internationalization/localization packages available, we simple could not find one that addresses the i18n/i10n problem in a simple yet extensible way for teams with more than one developer working on a single project. Most approches to the i18n/i10n problem using json implementation uses one file resulting to merge conflict nightmares. We created this package to adddress just this problem.

  • Configurable shared asset directory and translation files
  • Multiple translation json files per single supported locale i.e. support for modularize translation.
  • Use prefix to avoid overriding identical translation keys from different modules or packages

Install #

To use this package, add i18n_translator as a dependency in your pubspec.yaml file like so.

dependencies:
  i18n_translator: <version>

Add translation assets to your application in the assets section of your pubspec.yaml file as below. Ensure to define the root directory and the sub directories for each locale you plan to support. Note that each asset directory definition ends with a trailing / directory separator

assets:
    - assets/lang/
    - assets/lang/en/
    - assets/lang/fr/

Then run the flutter tooling:

flutter packages get

Create a json configuration file in the root translation directory you defined in the asset section above. When instantiating the Translator Provider or Delegate, you will have the opportunity to specify the path - relative to the root - to the configuration file and the root directory that contains the translation json files. An example config file may be as shown below.

{
  "en" : [
    {
      "prefix" : "module_1",
      "filename" : "en/module-1-en.json"
    },
    "en/module-2-en.json"
  ],
  "fr" : [
    {
      "prefix" : "module_1",
      "filename" : "en/module-1-fr.json"
    },
    "en/module-2-fr.json"
  ]
}

Usage #

See the main files provided with the accompanying example project for the different ways you may use this package.

We provided three options for you: Simple Provider, Bloc Provider and a Widget approach. We also made available "global" variable and function translator, translate and t to ease access to the i18n_translator provider/bloc and the translation functions that package users may call often.

Below is a quick example below that shows how to use the package. Do not forget to import relevant packages.

Simple Provider Approach #


// Define a static instance of the the Translator provider.
translator = TranslatorProvider(
  //Note: Keep locales as wide as possible. Use en instead of en_CM or en_US
  supportedLocales: [const Locale('en'), const Locale('fr')],
  langConfigFile: 'config.json',
  langDirectory: 'assets/lang/');

/// When material app is built, the load method of the delegate will be called
/// and the translator provider will load the translation strings.
/// This however results in a situation where translations are not loaded for
/// the home screen or page initially. To solve this, you may want to call
/// the method of the provider early but this results in loading twice.

// Call the load method directly from the provider
await translator.load();

// Get translation
translate('my_translation_key');
// Get translation with prefix
translate('my_translation_key', prefix: 'module_1');
// The line above is equivalent to this below
translate('module_1_my_translation_key');

Bloc Provider Approach #


// Define a static instance of the the Translator provider.
  translator = TranslatorProviderBloc(
      //Note: Keep locales as wide as possible. Use en instead of en_CM or en_US
      supportedLocales: [const Locale('en'), const Locale('fr')],
      langConfigFile: 'config.json',
      langDirectory: 'assets/lang/'
  );

  /// When material app is built, the load method of the delegate will be called
  /// and the translator bloc LoadEvent will fire loading the translation.
  /// The bloc will go to the LoadingState and then LoadedState.

// Load the translation by triggering a bloc event
translator.add(LoadEvent());

// Get translation
translatorProvider.translate('my_translation_key');
// Get translation with prefix
translatorProvider.translate('my_translation_key', prefix: 'module_1');
// The line above is equivalent to this below
translatorProvider.translate('module_1_my_translation_key');

Translator Widget Approach #


TranslatorWidget(
    supportedLocales : [const Locale('en'), const Locale('fr')],
    langConfigFile : 'config.json',
    langDirectory : 'assets/lang/',
    // provider : translator, //Only use if a singleton is instantiated - will override other provided variables
    child : Builder(
        builder: (context){

            // You may define a local variable
            final mProvider = BlocProvider.of<TranslatorWidgetBloc>(context).provider;

            // Or assign to the global translator provider variable from the package
            translator = BlocProvider.of<TranslatorWidgetBloc>(context).provider;

            return Container(
                child: Row(
                    children: [
                        Text(
                            // Usage with variable
                            mProvider.translate('my_translation_key', prefix: "module_1"), // This is called from mProvider
                        ),
                        Text(
                            // Usage with gloab translator variable
                            translate('my_translation_key', prefix: "module_1"), // This is called from translator
                        ),
                    ]
                ),
            );
        },
    )
);

Testing #

We have not yet implemented tests for the package. This shall be WIP as we continue to improve on the package.

flutter test

Credits #

  • Ideas for the Translator Widgets came from easy_localization

  • We want to thank specially Felix Angelov for his amazing work on flutter_bloc on which this package depends.

  • It is easy to forget those who make this possible; hats off to the Flutter Team and the amazing Flutter Community.

Dependencies #

This package depends on:

Contributions #

Contributions are always welcome!

Work with us #

  • hello[at]zingersystems.com
  • labs[at]zingersystems.com

License #

Copyright (c) 2020 MIT - Zinger Systems Limited

0.2.2 #

  • Removed locale plugins that where reporting issues.
  • Added support to get user preferred locale.

0.2.1 #

  • Modified plugin feature to get default system locales.

0.2.0 #

  • Added features to get default system locales.

0.1.9 #

  • Added reload option to Translator Bloc.

0.1.8 #

  • Added support to specify that delegate be reloaded. This may be handy during development.

0.1.7 #

  • Updated shared preference and flutter_bloc packages.

0.1.6 #

  • Updated Readme to reflect the new approach with proper examples.

0.1.5 #

  • Using mixin, created a Bloc version of TranslatorProvider called TranslatorProviderBloc. Also removed single instance method from the TranslatorProvider.

0.1.2 #

  • Edited package summary and readme files.

0.1.1 #

  • Minor formatting.

0.1.0 #

  • Implemented pub.dev health suggestions.
  • Moved package to a release version as we are convinced the package is ready for public use after two days of testing.

0.0.1 #

  • Initial Open Source release of i18n_translator.

example/lib/main.dart

import 'package:flutter/material.dart';

import 'package:i18n_translator/bloc/translator_provider_bloc/bloc.dart';
import 'package:i18n_translator/i18n_translator.dart';

void main() async {
  // Ensure bindings are initialized.
  WidgetsFlutterBinding.ensureInitialized();

  // Define a static instance of the the Translator provider.
  translator = TranslatorProviderBloc(
      //Note: Keep locales as wide as possible. Use en instead of en_CM or en_US
      supportedLocales: [const Locale('en'), const Locale('fr')],
      langConfigFile: 'config.json',
      langDirectory: 'assets/lang/',
      init: true
  );

  // When material app is built, the load method of the delegate will be called
  // and the translator bloc LoadEvent will fire loading the translation.
  // The bloc will go to the LoadingState and then LoadedState.

  // Run the app
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: translate(
          'app_title'), //Only use if a singleton is instantiated and loaded.
      supportedLocales: translator
          .supportedLocales, //Only use if a singleton is instantiated and loaded.
      localizationsDelegates: translator
          .delegates, //Only use if a singleton is instantiated and loaded.
      localeResolutionCallback: translator
          .resolveSupportedLocale, //Only use if a singleton is instantiated and loaded.
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(
          title: translate(
              'home_title') //Only use if a singleton is instantiated and loaded.
          ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              translate('pushed_number_of_times',
                  prefix:
                      "home_page_one"), //Only use if a singleton is instantiated and loaded.
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: translate(
            'increment'), //Only use if a singleton is instantiated and loaded.
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Use this package as a library

1. Depend on it

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


dependencies:
  i18n_translator: ^0.2.2

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:i18n_translator/i18n_translator.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
44
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
90
Overall:
Weighted score of the above. [more]
70
Learn more about scoring.

We analyzed this package on Jul 10, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.14
  • Flutter: 1.17.5

Analysis suggestions

Package does not support Flutter platform android

Because:

  • package:i18n_translator/i18n_translator.dart that imports:
  • package:i18n_translator/providers/translator_provider.dart that imports:
  • package:shared_preferences/shared_preferences.dart that imports:
  • package:shared_preferences_linux/shared_preferences_linux.dart that declares support for platforms: linux

Package does not support Flutter platform ios

Because:

  • package:i18n_translator/i18n_translator.dart that imports:
  • package:i18n_translator/providers/translator_provider.dart that imports:
  • package:shared_preferences/shared_preferences.dart that imports:
  • package:shared_preferences_linux/shared_preferences_linux.dart that declares support for platforms: linux

Package does not support Flutter platform macos

Because:

  • package:i18n_translator/i18n_translator.dart that imports:
  • package:i18n_translator/providers/translator_provider.dart that imports:
  • package:shared_preferences/shared_preferences.dart that imports:
  • package:shared_preferences_linux/shared_preferences_linux.dart that declares support for platforms: linux

Package does not support Flutter platform web

Because:

  • package:i18n_translator/i18n_translator.dart that imports:
  • package:i18n_translator/providers/translator_provider.dart that imports:
  • package:shared_preferences/shared_preferences.dart that imports:
  • package:shared_preferences_linux/shared_preferences_linux.dart that declares support for platforms: linux

Package does not support Flutter platform windows

Because:

  • package:i18n_translator/i18n_translator.dart that imports:
  • package:i18n_translator/providers/translator_provider.dart that imports:
  • package:shared_preferences/shared_preferences.dart that declares support for platforms: android, ios, linux, macos, web

Package not compatible with SDK dart

Because:

  • i18n_translator that is a package requiring null.

Health suggestions

Fix lib/i18n_translator.dart. (-0.50 points)

Analysis of lib/i18n_translator.dart reported 1 hint:

line 3 col 8: Unused import: 'package:flutter/material.dart'.

Format lib/providers/translator_provider.dart.

Run flutter format to format lib/providers/translator_provider.dart.

Maintenance issues and suggestions

Support latest dependencies. (-10 points)

The version constraint in pubspec.yaml does not support the latest published versions for 1 dependency (flutter_bloc).

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
flutter_bloc ^4.0.1 4.0.1 5.0.1
flutter_localizations 0.0.0
shared_preferences ^0.5.7+3 0.5.8
Transitive dependencies
bloc 4.0.0 5.0.1
collection 1.14.12 1.14.13
file 5.2.1
flutter_web_plugins 0.0.0
intl 0.16.1
meta 1.1.8 1.2.2
nested 0.0.4
path 1.6.4 1.7.0
path_provider_linux 0.0.1+2
path_provider_platform_interface 1.0.2
platform 2.2.1
plugin_platform_interface 1.0.2
process 3.0.13
provider 4.3.1
shared_preferences_linux 0.0.2+1
shared_preferences_macos 0.0.1+10
shared_preferences_platform_interface 1.0.4
shared_preferences_web 0.1.2+7
sky_engine 0.0.99
typed_data 1.1.6 1.2.0
vector_math 2.0.8 2.1.0-nullsafety
xdg_directories 0.1.0
Dev dependencies
flutter_test