2

I'm trying to use the intl plugin to get more translations of my app, but it always needs a context. In files without context where I simply have to assign a value to the variable what should I do?

For example I would like to do something like this::

String yes = "${AppLocalizations.of(context)!.yes}"
Jonathan
  • 106
  • 1
  • 8

3 Answers3

2

As other answers suggest you can put your variable inside build, however, if you don't want to do that then you can define a Navigator Key and get the current context from it anywhere in your code.

Define Navigator Key:

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

Attach it to your MaterialApp:

MaterialApp(
        navigatorKey: navigatorKey,
        ...
      ),

Get current context from navigatorKey:

String yes =  "${AppLocalizations.of(navigatorKey.currentContext!)!.yes}
Siddharth Mehra
  • 1,691
  • 1
  • 9
  • 32
0

If you use the GetX package, you can use

Get.context

to get a context in any piece of your code.

Ivo
  • 18,659
  • 2
  • 23
  • 35
-1

You can't access context outside of build method unless you pass it to a function.

  @override
      Widget build(BuildContext context) {
       String yes =  "${AppLocalizations.of(context)!.yes}" //like this
         ...
      }

if you don't want to do this. you need to change your AppLocalization static function.

brook yonas
  • 436
  • 3
  • 14
  • thanks for the answer but unfortunately in some circumstances I cannot put my variable inside a build method ... I have files containing only certain functions and attributes and there without context I cannot modify my values – Jonathan Sep 23 '22 at 04:58
  • Share you code and what you want to do. I just edited the answer – brook yonas Sep 23 '22 at 05:00