flutterdartinternationalizationmonorepo

Internationalization in a monorepo


I have an app (just frontend) whose code is structured in a monorepo. There are separate packages for each custom widget. I would also like to have one package with all the translations. In this way, if another package need a translation I just need to import that package. So I created the translation package and in its main file I just wrote (here I use intl):

export 'package:flutter_gen/gen_l10n/app_localizations.dart';

Now, if I import that package in another package and I import the file with:

import 'package:l10n/l10n.dart';

It tells me that that import is not used and gives me error when I use the translation with AppLocalizations.of(context)!.foo


Solution

  • It seems that it's not possible to export generated file by design (check out this github issue). The best solution that I've found to fix my problem is the following:

    1. Create a translation package inside your project, like in packages/translations and add that package to the pubspec.yaml of your your main project. Like this:
    dependencies:
      flutter:
        sdk: flutter
      translations:
        path: packages/translations
    
    1. In that package create a l10n.yaml file like this:
    arb-dir: lib
    template-arb-file: app_en.arb
    output-localization-file: app_localizations.dart
    synthetic-package: false
    
    1. If you are working in a git repo, add packages/translations/lib/app_localizations*.dart in your .gitignore
    2. Now if you run flutter packages get && flutter gen-l10n in that translations packages all the translations will be automatically generated (assuming they are in packages/translations/lib/app_xx.arb)
    3. Now you can import the translation file from you main package with import 'package:translations/app_localizations.dart';

    The only drawback is that the translations are not automatically generated when you type flutter pub get (see this issue). In order to regenerate them you have to type flutter gen-l10n inside the translations package every time. The solution could be improved by using a tool for managing Dart monorepo projects like melos.

    An example implementation of what I described (including melos) could be found in this github repo