9

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?

Taha Ali
  • 1,150
  • 9
  • 14

2 Answers2

2

I have implemented the same by following what is done in another package - Catcher. Here is the file - https://github.com/jhomlala/catcher/blob/master/lib/model/localization_options.dart

Braj
  • 588
  • 3
  • 15
-2

In order to generate localization files inside a package:

  1. Create localization files in .arb format
  2. add l10n.yaml file inside the root folder of the package with these settings:
# Where to find translation files
arb-dir: lib/l10n

# Which translation is the default/template
template-arb-file: app_en.arb

# What to call generated dart files
output-localization-file: app_localizations.dart
  1. make sure your main localization file and the 'template-arb-file' names are the same
  2. update 'dependencies' and 'flutter' in pubspec.yaml file of the package as below:
dependencies:
  flutter_localizations:
    sdk: flutter
  intl: ^0.17.0


flutter:
  uses-material-design: true
  generate: true
  1. run 'flutter pub get' inside the package root location
  2. Wrap your main UI widget with a MaterialApp
  3. Update MaterialApp as below
MaterialApp(
              localizationsDelegates: AppLocalizations.localizationsDelegates,
              supportedLocales: AppLocalizations.supportedLocales,
      ),
  1. Call the localization key inside a widget:
Text(AppLocalizations.of(context)!.helloWorld)

Note: Basically do almost same steps in official documentation inside your package root folder with a Custom MaterialApp https://docs.flutter.dev/development/accessibility-and-localization/internationalization

  • This is not very useful, as you're most likely _not_ going to use `MaterialApp` widget inside a package. – albru123 Mar 27 '23 at 15:00