How to Show Counter Badge on Icon, Button or Widgets in Flutter

In this example, we are going to show you how to show a counter badge on icons, icon buttons, buttons, or any widget in Flutter. The counter badge is very necessary on cart buttons, inbox buttons, orders like UI. See the example below for more details:

First, add badges Flutter package in your project by adding the following lines in pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  badges: ^2.0.2

Now, import the package in your script:

import 'package:badges/badges.dart';

Badge(
    child: Icon(Icons.shopping_cart),
    badgeContent: Text("3"),
)

The output will be like below:

Badge(
    child: Icon(Icons.shopping_cart, size: 40, color: Colors.green,), //icon style
    badgeContent: SizedBox(
        width: 20, height: 20, //badge size
        child:Center(  //aligh badge content to center
            child:Text("3", style: TextStyle(
               color: Colors.white,  //badge font color
               fontSize: 20 //badge font size
            )
          ),
        )
    ),
    badgeColor: Colors.purple, //badge background color
)

You can style the badge background color, icon, badge content like shown on the above code. The output will be like below:

Badge(
    position: BadgePosition.topStart(),
)

You can use the position property of Badge() widget to change the location of the badge. The output with the above position will look like below:

You can show badges on any kind of widget, you just need to pass your widget on the child property of Badge.

Badge(
    child: Card(), //you can replace with your widget
    badgeContent: Text("3"),
    position: BadgePosition.topStart(),
)

For example:

Badge(
    child: Card(
        child: Padding(
          padding:EdgeInsets.all(10),
          child: Icon(Icons.inbox),
        )
    ),
    badgeContent: Text("3",),
)

The output of the above code will look like below:

In this way, you can show counter badge/text badge on icon, icon button, or any kind of widget in Flutter. 

No any Comments on this Article


Please Wait...