-1

I am trying to show snackbar when user click the button but I can't do that.

I am not getting warning or error, I don't know what I am missing

here is my code:

RaisedButton(
   onPressed: () {
     if (formKey.currentState.validate()) {
       formKey.currentState.save();
       dbHelper
         .addNote(Notes(categoryID, notBaslik,
              notIcerik, "", selectedOncelik))
         .then((savedNoteID) {
       if (savedNoteID != 0) {
         _scaffoldKey.currentState
             .showSnackBar(SnackBar(
         content: Text("Not Eklendi"),
         duration: Duration(seconds: 2),
         ));
        } else {}
        Navigator.pop(context);
       });
      }
     },
     child: Text("Kaydet"),
     color: Colors.red),
 
Tolga KÜÇÜK
  • 123
  • 2
  • 10

2 Answers2

1

Make sure that, that you define a Scaffold in your widget tree where you are trying to show the snackbar and that _scaffoldKey is added as property to your scaffold i.e.

final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

Scaffold(key: _scaffoldKey, body: ...)

Alternatively you can use Scaffold.of(context)

Scaffold.of(context).showSnackBar(SnackBar(content: Text("Not Eklendi"), duration: Duration(seconds: 2));

like:

RaisedButton(
   onPressed: () {
     if (formKey.currentState.validate()) {
       formKey.currentState.save();
       dbHelper
         .addNote(Notes(categoryID, notBaslik,
              notIcerik, "", selectedOncelik))
         .then((savedNoteID) {
       if (savedNoteID != 0) {
         Scaffold.of(context).showSnackBar(SnackBar(
         content: Text("Not Eklendi"),
         duration: Duration(seconds: 2),
         ));
        } else {}
        Navigator.pop(context);
       });
      }
     },
     child: Text("Kaydet"),
     color: Colors.red),

In some cases you will need to wrap it in a Builder widget to get the right context. You cab try that if still not working

orotype
  • 449
  • 4
  • 8
0

Initialize a variable

final _scaffoldKey = GlobalKey<ScaffoldState>();

Add _scaffoldKey to Scaffold

Scaffold(
key: _scaffoldKey,
)

Code

RaisedButton(
   onPressed: () {
     if (formKey.currentState.validate()) {
       formKey.currentState.save();
       dbHelper
         .addNote(Notes(categoryID, notBaslik,
              notIcerik, "", selectedOncelik))
         .then((savedNoteID) {
       if (savedNoteID != 0) {
        final snackBar = SnackBar(content: Text("Test"));
        _scaffoldKey.currentState.showSnackBar(snackBar);
       
        } else {}
        Navigator.pop(context);
       });
      }
     },
     child: Text("Name"),
     color: Colors.red),
Abhijith
  • 2,227
  • 2
  • 15
  • 39