Display SnackBar at the top in Flutter apps

Vijay R
vijaycreations
Published in
3 min readJul 24, 2023

--

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.,👇

--

--

Vijay R
vijaycreations

Hai👋 I’m a flutter developer experienced in designing and developing stunning mobile apps. Reach out for freelance projects: calico.takeoff_01@icloud.com