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?
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
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
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.
Execute following commands to generate the localization files
flutter clean
flutter pub get
flutter gen-l10n # required command
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.
When publishing, also include the generated l10n files (i.e. lib/l10n
in the above l10n.yaml)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With