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'));
}
}
}
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 thecontext
will be obtained by aGlobalKey
that you to get from a widget that we can access theLocalization
widget context with it, which is inside theMaterialApp
of course.For this, you can use the
navigatorKey
to achieve it:Now that you assigned that key, you can create a
WithoutContextLocalizations
widget:Now from any place instead of using :
You can use :