Notification Badge in Flutter
This is my first article on Medium and it’s about Flutter. If you are reading this it probably means that you must have heard about Flutter SDK, Well for those who are not aware of it
Flutter is Google’s new SDK which allows you to build beautiful native apps on iOS and Android from a single codebase. To know more about Flutter click here
So in this article, I’m gonna share how you can achieve a Notification Badge in Flutter without using packages.
Here is a quick look at what we going achieve today
Basic Idea behind the notification badge
Using Stack
and Positioned
widgets we can stack the Text
widget over the IconButton
to show the notification badge.
Time to get hands dirty
Create a new Flutter Project and delete everything in main.dart
. Import the package and write the basic code which is required. Remove the debug banner in the app by assigning false
to debugShowCheckedModeBanner
debugShowCheckedModeBanner: false
Now, create a classMyApp
which extends StatefulWidget
and override the createState()
. createState()
should return an object of State
class. So, Create a new class _MyApp
which extends the State<MyApp>
and override the build()
method. To learn more about StatefulWidget click here.
Now create an instance variable of the type int
for_MyApp
and name it counter
. The variablecounter
will keep track of notification count. Thebuild()
method should return a Scaffold
widget. The purpose of returning Scaffold
from a StatefulWidget
is to change the count of notifications in notification badge.
In the above code snippet, we have created an App Bar and a Floating Action Button. In the onPressed
parameter of the FloatingActionButton
we are incrementing the value of counter
inside the setState()
.
Let’s use Stack
widget inside <Widget>[]
which is a list of widgets which is given to action
parameter of AppBar
. The Stack
widget has a parameter name children
which accepts the list of widgets <Widget>[]
. Create an IconButton
inside Stack
and use Positioned
widget to set the child of Positioned
widget which will a be Text
widget over the IconButton
. The Text
widget will be used to show the count of notifications.
In the above code, we are checking whether the value of counter
is greater than 0 to not. If the value of counter
is greater than 0, we will show the notification badge else will show an empty Container
. We are also setting counter
to 0 when IconButton
is pressed to remove the notifications.
Final Result
Click here to view Source Code
Hey Readers, I’m a Mobile Application Developer who loves to explore deep sea of Flutter widgets. If you liked this article and found this helpful don’t forget to appreciate by a 50 claps :p
If you have any questions or suggestions feel free to comment below or you can connect with me on
Checkout my Recent Articles