Localizing Flutter Packages

Hashem Abounajmi
2 min readFeb 12, 2022

Assume you know localization in Flutter, but if you are not familiar you can read the recommended guide from Flutter docs. Now let’s back to the question: You have a main app with multiple feature packages and you want by changing main app locale, locale reflected to the other packages. How to do this?

Let’s have an example: A main app that has dependency to shopping cart package.

Localizaing Main App

For the main app localization follow the Flutter tutorial.

Localizing Shopping Cart Package

We have only one MaterialApp widget which is in the main app package and we should set flutter localization delegates + each package localization delegate:

MaterialApp(  localizationsDelegates: AppLocalizations.localizationsDelegates +  [ShoppingCartLocalizations.delegate],  supportedLocales: AppLocalizations.supportedLocales,  home: const HomePage(),);

In the shopping cart package create l10n.yaml file and add below configuration:

preferred-supported-locales: [en, fa]synthetic-package: falseoutput-dir: ./lib/src/l10n/generatedarb-dir: ./lib/src/l10ntemplate-arb-file: intl_en.arboutput-localization-file: shopping_cart_localizations.dartoutput-class: ShoppingCartLocalizations

For the package the trick is here we should tell flutter where to generate localization files and then we add the generated file path to package export file so localization will be accessed outside of the package. The important configuration properties are: synthetic-package, output-dir, arb-dir. By setting synthetic-package to false we tell flutter don’t create your localization package. The output-dir sets where the generated files should go. The arb-dir tells where to lookup for arb files.

Now in terminal go to the shopping_cart package and then run the flutter localization generation command:

flutter gen-l10n

Then shopping_cart package localization files are generated:

Open your package export file, for my case it is shopping_cart.dart. It contains list of files of this package that are accessible to other packages. Add generated localization file path:

export 'src/l10n/generated/shopping_cart_localizations.dart';

Finally in the MaterialApp widget add ShoppingCartLocalizations delegate to the list of localizations delegates.

I tried to simplify as much as possible and main point was showing the trick. but as I said initially you have to know Flutter localization before jumping to this article.

You can download the sample code from Github

--

--