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}"
2
  • you can put this in the build method Commented Sep 23, 2022 at 4:40
  • Use AppLocalizations.current.yes Commented Sep 23, 2022 at 5:33

3 Answers 3

4

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}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

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
Share you code and what you want to do. I just edited the answer
0

If you use the GetX package, you can use

Get.context

to get a context in any piece of your code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.