Flutter Access parent Scaffold from different dart file

You should try to avoid using GlobalKey as much as possible; you're almost always better off using Scaffold.of to get the ScaffoldState. Since your menu is below the scaffold in the widget tree, Scaffold.of(context) will do what you want.

The reason what you're attempting to do doesn't work is that you are creating two seperate GlobalKeys - each of which is its own object. Think of them as global pointers - since you're creating two different ones, they point to different things. And the state should really be failing analysis since you're passing the wrong type into your Drawer's key field...

If you absolutely have to use GlobalKeys for some reason, you would be better off passing the instance created in your outer widget into your Menu class as a member i.e. this.scaffoldKey, but this isn't recommended.

Using Scaffold.of, this is what your code would look like in the onTap function:

onTap: () {
  // On tap this, I want to show a snackbar.
  Scaffold.of(context).showSnackBar(showSnack('Error. Could not log out'));
},

Tags:

Dart

Flutter