How to show SnackBar in Flutter using Global key


Flutter shows snack bar using Scaffold. First create an instance of Snackpbar and then use Scaffold and contest to invoke Showsnackbar method.

var info = SnackBar(content: Text('Project Updated'));
Scaffold.of(context).showSnackBar(info);

Won’t work

This don’t work ? There are other method that should work, which involves the following.

  • ¬†
  • Create ScaffoldState Global Key
  • Use it in Scaffold
  • Use CurrentState.ShowSnackBar method to Showsnackbar

 

 

Create a global key variable and apply the key to in your StatefullWidget as follows

class _MyHomePageState extends State<MyHomePage> {
  final _globalKey = GlobalKey<ScaffoldState>();
.........
}

Add the key to scaffold widget

 Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        key: _globalKey,
.....
.....

and show the SnackBar using key

var info = SnackBar(content: Text('Project Saved'),);
_globalKey.currentState.showSnackBar(info);

It should work. These Flutter posts may help you

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.