How to access flutter localization without a context

1.2k Views Asked by At

I am using flutter localization from their official documentation here, and I am using clean architecture in my project. I want to access the app localization class without a context so I can translate the error messages in the repository file.

Here is an example:

class UserRepository{
  Future<Either<Failure, Unit>> logOut() async{
    try{
      return const Right(unit);
    }catch(e){
      return const Left(AuthFailure('I want to translate this error based on app`s language'));
    }
  }
}
2

There are 2 best solutions below

0
On BEST ANSWER

Well, since this is not the best practice to do, you can create a custom localizations widget that gets you the Localizations.of(context) but here the context will be obtained by a GlobalKey that you to get from a widget that we can access the Localization widget context with it, which is inside the MaterialApp of course.

For this, you can use the navigatorKey to achieve it:

// somewhere else in your project
GlobalKey<NavigatorState> ourNavigatorKey = GlobalKey<NavigatorState>();

// main.dart
MaterialApp(
  navigatorKey: ourNavigatorKey,
//...

Now that you assigned that key, you can create a WithoutContextLocalizations widget:

Localizations withoutContextLocalizations() {
  final BuildContext context = ourNavigatorKey.currentContext!;
  return Localizations.of<Localizations>(context, Localizations)!;
}

Now from any place instead of using :

Localizations.of(context);

You can use :

WithoutContextLocalizations();
0
On

here is another solution since it is not best practice to use context inside data classes.

you can create a singleton class like this:

class LocalizationManager {
  static final LocalizationManager instance = LocalizationManager._();
  LocalizationManager._();

  late AppLocalizations _localization;

  AppLocalizations get appLocalization => _localization;

  void setLocalization(BuildContext context) {
    _localization = AppLocalizations.of(context)!;
  }
}

then in the material app builder, set the value of localization:

return MaterialApp(
  builder: (context, child) {
    LocalizationManager.instance.setLocalization(context);
    return child!;
  },
)