top of page
  • Writer's pictureJohn N Blanchard

Flutter: Snackbar

In many apps, I find myself making views that pop up or pop down and show some feedback to the user. If I were to do this with iOS I would set the initial top constraint below superview.bottom with some constant that is equal to the height of the view. In Android we have this nice Snackbar, a bottom view that pops up onto the screen. It has implementations for showing data, and animating.

Flutter has a Snackbar too. I found it quite handy for making interaction in my app more informative. In the tip calculator, I use this widget to create a bottom bar that shows a user their total.

There are a few ways to go up a widget tree and handle displaying our Snackbar. The problem with Snackbar is that you can only call its show command from the singleton Scaffold. So I elected to hold around a key that will point me to the correct widget for displaying our bottom information.

Wait, that's kinda bad though. In order to reach scaffoldKey, every widget that uses Snackbar would need another state parameter. I hate that. Instead our lower widgets will use an inherited widget (Scaffold) to reach for Snackbar actions.

Now we can remove the key. This will be what we'll call if at any point we want to show the Snackbar. Any lower widget in our tree is able to take this short-cut.

When we wish to dismiss the Snackbar, we again use the inherited widget to reach the implementation. Otherwise in order to reach the Snackbar state, I would need to declare a new parameter for my Scaffold's key. When building my lower widgets that key would be passed around and used below.

The scaffoldKey will have a currentState property capable of reaching our Scaffold state. Any lower widget that interacts with the Snackbar will need to declare a scaffoldKey. Or one could simply use inheritance to reach up our widget tree and grab the Snackbar state. I prefer the latter but you can try it out for yourself, here's the project so far.

58 views0 comments

Recent Posts

See All
bottom of page