Home > Back-end >  How to get context in a simple class without BuildContext in flutter
How to get context in a simple class without BuildContext in flutter

Time:10-28

I am using this package plugin flutter_locales for app localization. So check the current language code by using this is the code.

LocaleNotifier.of(context)!.locale!.languageCode;

Now problem is if i use this code inside in simple class which gives an error on "context".

class Service {
  var lang = LocaleNotifier.of(context)!.locale!.languageCode; // getting error on "context"
}

So how prevent this "context" error without BuildContext in Service class?

CodePudding user response:

You simply don't. You will need to pass in the BuildContext context to your Service class.

Try this:

class Service {
  final BuildContext context;

  Service(this.context);

  String get lang => LocaleNotifier.of(context)!.locale!.languageCode;
}

Then pass in the context when creating this class.

  • Related