flutterdartflutter-localizations

How to access flutter localization without a context


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'));
    }
  }
}

Solution

  • 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();