Home > front end >  how to use intl flutter without context?
how to use intl flutter without context?

Time:09-23

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}"

CodePudding user response:

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}

CodePudding user response:

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.

CodePudding user response:

If you use the GetX package, you can use

Get.context

to get a context in any piece of your code.

  • Related