DEV Community

loading...
Cover image for Displaying snackbar in flutter while navigating

Displaying snackbar in flutter while navigating

baksman profile image ibrahim Shehu ・2 min read

The technologies/tools that we will be using in this tutorial are
Pc (windows,Mac,Linux) any one you like to code inπŸ˜ƒ
Flutter
Vscode
And also I will be assuming you have Flutter and Vscode already set up,so lets start

Sometimes we wish to display a snackbar to our users while they navigate to a new route/screen,a very good usecase of this is when token gets expired while users are using the application and we routed them to login screen, we ought to show them a notification to signify that the application didnt malfunction, though snackbars are not the only form of notification/popup we could give users in flutter but its usually prefered beacuse it doesn`t take the focus of the user away from the app since it displays at the bottom of the screen.
That seems easy right? the naive way is to call navigator then call the snackbar method just like this

flutter

If you run the code snippet above you will discover that it doesn`t work, this is simply because we are calling Snackbar from a screen different from the context(previous screen) we gave to it.
The next thing that might come into your mind is to call snackbar in the login screen either in build or initstate method that wont work because at that point in time flutter is already rendering the widget tree and and internally flutter sees snackbar like a new screen trying to build a screen while building a screen ?? huhh?? It throws an error
image

WidgetsBinding to the rescue

What this widget simply does is that it waits for flutter to finish rendering before calling the function wrapped iniside of it, So we can add the code below to either initState or build method to the screen we are navigating to
Flutter
Done !!

Discussion (0)

pic
Editor guide