Arjit Bhamu
Arjit Bhamu

Reputation: 63

Undefined name 'context' in fuction

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

Upvotes: 0

Views: 1174

Answers (3)

Arjit Bhamu
Arjit Bhamu

Reputation: 63

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.

Upvotes: 0

Sujan Gainju
Sujan Gainju

Reputation: 4769

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.

Upvotes: 1

Riwen
Riwen

Reputation: 5190

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.

Upvotes: 2

Related Questions