Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add localization support inside Flutter packages

I am creating a Flutter package that has some text inside it. I want the consumer application of my package to pass locale to it, based on that locale my package should decide whether to show this text in 'Arabic' or 'English' (This means my package will have resource file containing strings inside it for these locales). How can I achieve this?

The only thing I was able to achieve was that my consumer application has the resource file and both my consumer application and package have to register the same localization plugin as dependency. I do not want my consumer app to worry about localization and instead my package should handle showing of translated strings based on locale. Is there anything wrong with my approach?

like image 562
Taha Ali Avatar asked Sep 14 '25 01:09

Taha Ali


1 Answers

Since then, Flutter team has introduced their own localization support. This answer aims to integrate official solution and adapting it into use for packages.

The key is to configure flutter l10n to generate output in out library package instead of .dart_tool by setting synthetic_package: false in l10n.yaml

  1. Edit l10n.yaml
arb-dir: lib/l10n
output-dir: lib/l10n
template-arb-file: <your_package>_en.arb
output-localization-file: <your_package>_localizations.dart
nullable-getter: false
use-escaping: true
synthetic-package: false # this line
output-class: <your_package_class> # e.g. MyPackageLocalizations
  1. Add flutter_gen in dev_dependencies (ref) in pubspec.yaml, in addition to build_runner. I ran the command flutter pub add flutter_gen --dev in command line to ensure I get the newest available version.

  2. Execute following commands to generate the localization files

flutter clean
flutter pub get
flutter gen-l10n # required command
  1. In your code where localization is needed, instead of importing import 'package:flutter_gen/gen_l10n/app_localizations.dart';, import import 'package:<your_package>/l10n/<your_package>_localizations.dart'; instead. Android Studio should be able to pick it up and offer quick fixes for this.

  2. When publishing, also include the generated l10n files (i.e. lib/l10n in the above l10n.yaml)

  3. Dependent apps will still need to include localization delegates in their MaterialApp constructor, as instructed here. Particularly, they will need to include your libraries' custom <your_package_class>.delegate. Make this clear in your README Usage guides.

like image 72
luiges90 Avatar answered Sep 15 '25 16:09

luiges90