Home > Net >  Undefined name 'context' in fuction
Undefined name 'context' in fuction

Time:05-27

I defined a showSnackBarr() function in any separate dart file and used in other dart file but showing red line under this stared ** context.

showSnackBar( **context** , e.toString);

showSnackBar(BuildContext context, String text) {
  return ScaffoldMessenger.of(context).showSnackBar(SnackBar(
    content: Text(text),
  ));
}
on FirebaseAuthException catch(e){

      showSnackBar(context, e.message!);
      res = false;
}

CodePudding user response:

There is no variable/instance member called context where you're invoking your function. Generally, context is available as a property in State objects. An instance of BuildContext is also passed into the build method of Widgets.

More on BuildContext.

CodePudding user response:

Seems like you are trying to show the snackbar from the function outside of the widget.

For that, you have to pass the BuildContext to the function along with any parameters.

Example:

void myFunc(BuildContext context, dynamic data){
    try{
        // perform operation
    }
    catch(e){
        showSnackBar(context, e.message!);
    }
}

and call the function from the widget as

myFunc(context, "any data");

OR

you can use global context if you do not want to pass the build context each time.

CodePudding user response:

I did this that I intialize a variable into the class where I using this function it is working final BuildContext context ; AuthMethods({required this.context });

And make a constructor.

  • Related