Home > OS >  how to access context member in dart class?
how to access context member in dart class?

Time:01-22

im trying to access a field(a build context) in my class and it says: The instance member 'context' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression here is my class:

CustomMaterialTheme({
required final this.fontFamily,
required this.context});

final newTextTheme = Theme.of(context).textTheme.apply(
    bodyColor: CustomTaavTheme.textColor,
    displayColor: CustomTaavTheme.textColor,
  );

CodePudding user response:

I'm not sure why you're trying to do required final this.fontFamily which is obviously wrong, you should read this https://dart.dev/guides/language/language-tour

CodePudding user response:

i solved this problem with setting a global key to materialApp like this:

MaterialApp(
  key: ServiceChargeModuleUtils.materialKey,)

and access its context like this:

ServiceChargeModuleUtils.materialKey.currentContext!

CodePudding user response:

Your are not accessing context from inside your class, but from an initializer as the error message stated. In an initializer you have no access to this, because the instance is not created yet. To learn about initializers, look here: https://dart.dev/guides/language/language-tour#initializer-list

You can do the assignment in the body of your constructor. But then you have to mark newTextTheme as late.

  •  Tags:  
  • Related