rosetta_generator 0.1.3

  • Readme
  • Changelog
  • Example
  • Installing
  • 62

rosetta_generator #


Generates Helper classes for localization files, which can be used with flutter_localizations library.

Configuration #

  1. Add rosetta to pubspec.yaml under the dependencies: section. The latest version is Pub
    sdk: flutter
    sdk: flutter
  rosetta: ^latest_version
  1. Add build_runner and rosetta_generator under the dev_dependencies: section of the pubspec.yaml file. The latest version is Pub
  build_runner: '>=0.10.3 <1.2.0'
  rosetta_generator: ^latest_version
  1. Add (or modify) the build.yaml file in the same folder as the pubspec.yaml and include the rosetta builder. Also if you placed your translation files outside the lib folder, you need to declare the path to be included in the generator build step.
    sources:        // These lines with comments show how to declare the additional folders
      include:      // which contain the translations. In our case the i18n folder. Sadly
        - i18n/**   // if declare the include block we need to specify all our source folders
        - lib/**    // also.

Usage #

In your library add the following import:

import 'package:rosetta/rosetta.dart';

Create a class containing two static members which will be used later for localization:

class Translation {
  static LocalizationsDelegate<Translation> delegate;

  static Translation of(BuildContext context) {
    return Localizations.of(context, Translation);

Annotate the class with the rosetta Stone annotation. The path parameter should point to a directory containing the [languageCode].json localization files.

@Stone(path: 'i18n')
class Translation {
  static LocalizationsDelegate<Translation> delegate;

  static Translation of(BuildContext context) {
    return Localizations.of(context, Translation);

Include the part directive indicating the file that will be generated (typically the same file with a .g extension before .dart):

part 'rosetta_generator_example.g.dart';

Run build_runner:

flutter packages pub run build_runner build

Note: On first attempt to run this command you might encounter a conflict error. If so, please add the --delete-conflicting-outputs argument to your command:

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

(This additional argument allows the command to overwrite the .g.dart file if necessary.)

You can also use the watch command instead of build. This will generate your file when it's saved.

flutter packages pub run build_runner watch

This process will generate 3 classes (let's assume that the annotated class was called Translation as in the example above):

  • _$Keys: Contains all your keys as static fields, this is currently for internal use.
  • _$TranslationDelegate: This is an implementation of LocalizationsDelegate<Translation>, this should be passed to MaterialApp or CupertinoApp as a localization delegate. Also should be passed to the static delegate attribute of your original class.
  • _$TranslationHelper: An abstract class, which is meant to be used as an abstract base or mixed in to your annotated class. Contains functions to access the localized strings for each key (ex.: String get emptyList => _translate(_$Keys.emptyList);).

If you apply the generated classes you will end up something like this:

@Stone(path: 'i18n')
class Translation with _$TranslationHelper { // Generated mixin class or you can extend it also
  static LocalizationsDelegate<Translation> delegate = _$TranslationDelegate(); // Generated delegate

  static Translation of(BuildContext context) {
    return Localizations.of(context, Translation);

You can now start using your localization logic:

class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text(
          	/// Returns a string repesented with a key "hello_there" in the localization files.
      localizationsDelegates: [
      	/// Returns the generated delegate, which will setup the [Translation] instances.
      supportedLocales: [
        const Locale(SupportedLocales.english),
      theme: ThemeData(

The generated code backing the above functionality looks something like this (changes according to translation input):

class _$TranslationDelegate extends LocalizationsDelegate<Translation> {
  bool isSupported(Locale locale) => ["en"].contains(locale.languageCode);

  bool shouldReload(LocalizationsDelegate<Translation> old) => false;

  Future<Translation> load(Locale locale) async {
    var translations = Translation();
    await translations.load(locale);
    return translations;

class _$Keys {
  static final String helloThere = "hello_there";

  static final String seeYouSoon = "see_you_soon";

abstract class _$TranslationHelper {
  Map<String, String> _translations;

  Future<void> load(Locale locale) async {
    var jsonStr =
        await rootBundle.loadString("i18n/${locale.languageCode}.json");
    Map<String, dynamic> jsonMap = json.decode(jsonStr);
    _translations = jsonMap
        .map<String, String>((key, value) => MapEntry(key, value as String));

  String _translate(String key) => _translations[key];

  String get helloThere => _translate(_$Keys.helloThere);
  String get seeYouSoon => _translate(_$Keys.seeYouSoon);

Interceptors #

In most cases we will end up with some kind of parametrization in some of our resouces, like displaying currencies, amount, etc... This is where interceptors can help us.

We can define our interceptor logic in @Stone annotated classes using @Intercept annotations. The annotation has two variants @Intecept.simple(), which describes interceptor logic for all resources, and @Intercept.withFilter(filter), which provides custom logic for resources matching the provided filter pattern.

The below example shows our previous Translations class with interceptors.

@Stone(path: 'i18n')
class Translation with _$TranslationHelper { // Generated mixin class or you can extend it also
  static LocalizationsDelegate<Translation> delegate = _$TranslationDelegate(); // Generated delegate

  static Translation of(BuildContext context) {
    return Localizations.of(context, Translation);
  @Intercept.withFilter(filter: r'%(?:(\d+)\$)?([\+\-\#0 ]*)(\d+|\*)?(?:\.(\d+|\*))?([a-z%])')
  String paramIntercept(String translation, var args) => sprintf(translation, args);

  String simpleIntercept(String translation) => ">>> $translation";  

The current generator logic doesn't support interceptor cascades, so only one interceptor will be applied to one tranlsation key. The logic always picks up the first matching interceptor for a key. If there's no matching interceptor it falls back to the original getter logic (simply returns what's defined in the JSON).

So, in the above example, if we have a key, which has atleast one matching translation for the provided filter, then the paramIntercept interceptor will be used, otherwise the simpleIntercept which is applied to all (remaining) keys.

The interceptor function must return String and also has to declare a String parameter as it's first parameter. After the first parameter you can declare other parameters if you like, but keep in mind, that all accessors generated for the matching keys will have the same parameters as the tailing ones following the first string input.

The interceptors in the examples will produce accessor methods like below:

String get helloLabel => simpleIntercept(_translate(_$Keys.helloLabel));


String helloLabel(var args) => paramIntercept(_translate(_$Keys.helloLabel), args);

If we swap the two interceptors then the simpleIntercept method will be applied to all keys, because it matches any. And the filtering one will be applied to the remaining ones (which is an empty set of keys).

v0.1.3 #

Improvements: #

  • Add support for Rosetta's grouping attribute
  • Changed analyzer dependency version
  • Code quality improvements

v0.1.2 #

Improvements: #

  • Add generator logic for Stone.package attribute to enabled support for multi-package projects.

v0.1.1 #

Improvements: #

  • Add generator logic for @Intercept annotations.
  • Add validation logic for annotations and for their parameters.
  • Improved generator error messages

Fixes: #

  • build_runner watch will now detect correctly the referred JSON file changes.

First release version #

Add generator logic for @Stone annotation.


import 'dart:async';
import 'dart:convert';

import 'package:rosetta/rosetta.dart';

import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

part 'rosetta_generator_example.g.dart';

@Stone(path: 'i18n')
class Translation with _$TranslationHelper {
  static LocalizationsDelegate<Translation> delegate = _$TranslationDelegate();

  static Translation of(BuildContext context) {
    return Localizations.of(context, Translation);

Use this package as a library

1. Depend on it

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

  rosetta_generator: ^0.1.3

2. Install it

You can install packages from the command line:

with pub:

$ pub get

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

3. Import it

Now in your Dart code, you can use:

import 'package:rosetta_generator/generator.dart';
Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

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

  • Dart: 2.7.0
  • pana: 0.13.4

Health suggestions

Fix lib/src/tree/implementation/node.dart. (-0.50 points)

Analysis of lib/src/tree/implementation/node.dart reported 1 hint:

line 36 col 58: Do not pass null as an argument where a closure is expected.

Maintenance issues and suggestions

Support latest dependencies. (-40 points)

The version constraint in pubspec.yaml does not support the latest published versions for 4 dependencies (analyzer, build, dart_style, recase).


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0 <3.0.0
analyzer >=0.32.4 <0.37.0 0.36.4 0.39.4
build >=0.12.6 <1.2.0 1.1.6 1.2.2
code_builder ^3.1.3 3.2.1
dart_style >=1.0.0 <1.3.0 1.2.9 1.3.3
glob ^1.1.0 1.2.0
path ^1.6.2 1.6.4
recase ^2.0.0+1 2.0.1 3.0.0
rosetta ^0.1.3 0.1.3
source_gen ^0.9.1 0.9.4+4 0.9.4+7
Transitive dependencies
args 1.5.2
async 2.4.0
built_collection 4.3.2
built_value 7.0.8
charcode 1.1.2
collection 1.14.12
convert 2.1.1
crypto 2.1.4
csslib 0.16.1
fixnum 0.10.11
front_end 0.1.19 0.1.29
html 0.14.0+3
js 0.6.1+1
kernel 0.3.19 0.3.29
logging 0.11.4
matcher 0.12.6
meta 1.1.8
node_interop 1.0.3
node_io 1.0.1+2
package_config 1.1.0
pedantic 1.9.0
pub_semver 1.4.2
quiver 2.1.2+1
source_span 1.6.0
stack_trace 1.9.3
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
watcher 0.9.7+13
yaml 2.2.0
Dev dependencies
build_runner ^1.1.0