Display SnackBar at the top in Flutter apps
In this article we will discuss about how to add snackbar at the top in our flutter apps
🎥 Video Tutorial
🔭 Implementation
By default whenever we try to display the snackbar in our Flutter app, it appears at the bottom. But if there is use-case or scenario, where we were asked to display the snackbar at the top of our flutter app, near the app bar then this article is just for you!
We don’t need to add any packages for doing this. Moreover there isn’t any fixed or clear solutions for achieving the same. But yet there is a simple workaround, where we can play around with the margin values to get the job done.
→ Create a SnackBar
Let’s first create a default (which appears at the bottom) snackbar , that will be displayed upon button press event (as shown below👇).
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('SnackBar Demo'),
backgroundColor: Colors.pink.withOpacity(0.7),
),
body: Center(
child: ElevatedButton(
onPressed: () => showSnackBarFun(context),
child: const Text('Show Snackbar'),
)),
);
}
showSnackBarFun(context) {
SnackBar snackBar = SnackBar(
content: const Text('Yay! A SnackBar at the top!',
style: TextStyle(fontSize: 20)),
backgroundColor: Colors.indigo,
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
→ Add margin values
Now in-order to make the snackbar appear at the top, we need to specify the margin values and set the SnackBehaviour as floating., Therefore the previous code can be re-written as follows.,
showSnackBarFun(context) {
SnackBar snackBar = SnackBar(
content: const Text('Yay! A SnackBar at the top!',
style: TextStyle(fontSize: 20)),
backgroundColor: Colors.indigo,
dismissDirection: DismissDirection.up,
behavior: SnackBarBehavior.floating,
margin: EdgeInsets.only(
bottom: MediaQuery.of(context).size.height - 150,
left: 10,
right: 10),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
Well that’s it. 🎉 Run the code to see it in action.🥳
Refer my video tutorial for complete guide:👉 https://www.youtube.com/watch?v=2k_bgoeXkmg
Get the complete source code here:👉 https://github.com/vijayinyoutube/snack_bar_top_public
Check out all my Flutter related blogs here.,👇
Other articles you may like.,
🔵Setting up your Flutter app for publishing in Play Store.
🔴Confetti Animation in Flutter
🟡 Change App Launcher Icon in Flutter
🔴 AnimatedContainer Widget in Flutter
Most popular
Flutter Tutorials
If you found this article useful and wish to support my work, you can consider buying me a ☕️ coffee.👇
If you want to know more about Flutter and various Widgets in Flutter…?🤓 Then visit my channel 👉🏻 vijaycreations🚩
Thanks.,