0

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;
}
Riwen
  • 4,734
  • 2
  • 19
  • 31

3 Answers3

2

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.

Riwen
  • 4,734
  • 2
  • 19
  • 31
  • I did this that I intialize a variable into class add it is working final ```BuildContext context ; AuthMethods({required this.context });``` Thank you so much Sir!! – Arjit Bhamu May 26 '22 at 12:35
1

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.

Sujan Gainju
  • 4,273
  • 2
  • 14
  • 34
0

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.