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

2

13

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!

Setaceous answered 11/4, 2022 at 5:51 Comment(0)
S
6

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.
Sanfo answered 15/4, 2022 at 18:20 Comment(1)
I agree that this should generally be avoided in BLOCs, but it makes total sense when using Text to Speech from a library.Stock
O
0

It's actually really easy to achieve by using easy_localization package. You don't need context, the string can be accessed like that:

final text = LocaleKeys.books_details_delete.tr();

The only downside to this solution is that it uses code generation, so you need to rebuild the project after string changes.

For more details, I have written an example app with tutorial.

Outfight answered 4/1, 2023 at 20:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.