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!
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:
Short example:
import 'package:get_it/get_it.dart';
GetIt getIt= GetIt.instance;
void setupServiceLocator() {
getIt.registerLazySingleton(() => AppLocalizations());
}
AppLocalizations i10n = await AppLocalizations.delegate.load(Locale('en'));