0

Please before mark it as duplicate take a look, I have been trying this thread but i can't make it work. I am trying to make my learning app to display a snackbar, and yes i ran the google cookbook sample and it works, but i am trying to challenge my self doing something else, basically what it is, is just a scaffold with two buttons that increase and decrease, when the index is zero i want to display a snackbar that index is zero, can't decrease more than that. So i got this button and onPressed method calls _onTapPrevious method which passed the context parameter, but i am not sure this is the correct way to pass the context.

new RaisedButton( 
  padding: const EdgeInsets.all(8.0),
  textColor: Colors.white,
  color: Colors.redAccent,
  onPressed: () => _onTapPrevious(context),
  child: new Text("Previous"),
),

Here is the _onTapPrevious method that i created a snackbar, and also checks whether the widget index is > than 0 and if so it can decrease the index, and when it reaches 0 then it should display the snackbar.

_onTapPrevious(BuildContext context) {
    final snackBar = SnackBar(content: Text("Index 0, can't decrease more."));
    setState(() {
      if (widget.index > 0) {
        widget.index--;
      } else {
       Scaffold.of(context).showSnackBar(snackBar);
     }
    });
  }

The error that i get:

flutter: Another exception was thrown: Scaffold.of() called with a context that does not contain a Scaffold.
Sachihiro
  • 1,597
  • 2
  • 20
  • 46

1 Answers1

1

try to add

final _scaffoldKey = GlobalKey<ScaffoldState>();

to your class, then in Scaffold:

 key: _scaffoldKey,

and finally:

_scaffoldKey.currentState.showSnackBar(snackBar);

Hope that helps!

Mantykora
  • 36
  • 4
  • I did exactly this, just a moment ago before you wrote this solution, and just when i was deleting this question, it came the notification that you wrote an answer, but thanks man anyway, and i am keeping it and also marking as a solution. :) – Sachihiro Jun 10 '19 at 22:01