Search code examples
flutterlocalizationinternationalizationbloccubit

How to use flutter internationalization inside BLOC, Cubit And Repositories for translate messages?


I am working on a multilingual app in Flutter.

I used flutter_localizations package for localization and intl package for internationalization.

In the normal way inside Widgets, I can use it with help of Context.

But the problem is when I want to use internationalization inside repositories or other layers except for the UI layer.

What is the best practice for doing internationalization inside Other layers except for UI (where we don't have access to Context) for example using internationalization inside Api, Repository, Bloc, or Cubit?

Note: I'm looking for a way to use internationalization inside BLOC (business logic) of the app, not UI!


Solution

  • Generally speaking, it's better to avoid using localization outside the UI layer. If you are using BLoC library, you can show dialogs, snackbars, and similar widgets in BlocListener. You can also write an extension for your state to handle localization in the UI layer.

    However, there are ways to use localization without BuildContext. For example:

    • You can use a service locator like GetIt to access the AppLocalizations. With help of GetIt, you would be able to access the instance by type, without context. But in the case of AppLocalizations, we need to register it as a singleton / lazy singleton. Note, that you need to provide this exact singletons delegate to your app, so you will access the same object as in the list of localization delegates.

    Short example:

    import 'package:get_it/get_it.dart';
    
    GetIt getIt= GetIt.instance;
    
    void setupServiceLocator() {
      getIt.registerLazySingleton(() => AppLocalizations());
    }
    
    • You can access the instance of your LocalizationsDelegate by loading it directly and by specifying the locale. For example:

    AppLocalizations i10n = await AppLocalizations.delegate.load(Locale('en'));

    • You can use different localization library, which does not require a context to access the translations object (like easy_localization). By using code generation, you would be able to access your translation keys without a context.