0

I can't seem to figure out why this isn't working. I'm supposed to get a snackbar when I tap the button. Any help? The code snippet on flutter api works fine tho


void main() => runApp(SnackBarDemo());

class SnackBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          body: Center(
            child: InkWell(
              // When the user taps the button, show a snackbar.
              onTap: () {
                Scaffold.of(context).showSnackBar(SnackBar(
                  content: Text('Tap'),
                ));
              },
              child: Container(
                padding: EdgeInsets.all(12.0),
                child: Text('Flat Button'),
              ),
            ),
          )
        )
      )
    );
  }
}

aNoNyMoUs
  • 61
  • 7
  • https://stackoverflow.com/a/52309748/7652758 Hope this helps you. – ibhavikmakwana Apr 27 '20 at 09:29
  • Does this answer your question? [How to show a SnackBar in callback onEvent of EventChannel.listen](https://stackoverflow.com/questions/52308087/how-to-show-a-snackbar-in-callback-onevent-of-eventchannel-listen) – HII Apr 27 '20 at 09:50

1 Answers1

0

You are calling showSnackbar in a widget on the same level of the Scaffold, so the context you are sending to this method does not contain a Scaffold,

Soltuion: make this widget one level below the Scaffold:

void main() => runApp(SnackBarDemo());

class SnackBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: SafeArea(
            child: Scaffold(
                body: Center(
                  child: Builder(
                    builder: (context)=>InkWell(
                      // When the user taps the button, show a snackbar.
                      onTap: () {
                        Scaffold.of(context).showSnackBar(SnackBar(
                          content: Text('Tap'),
                        ));
                      },
                      child: Container(
                        padding: EdgeInsets.all(12.0),
                        child: Text('Flat Button'),
                      ),
                    ),
                  ),
                )
            )
        )
    );
  }
}
HII
  • 3,420
  • 1
  • 14
  • 35