Create icon badges in Flutter to display notifications

Badges are small visual markers that show important information to users quickly. They can highlight new messages, show unread notifications, or indicate item quantities. This post will teach you two ways to create badges in Flutter. You will learn how to create badges using Flutter’s built-in widgets and using the Badges package for an easier approach.

Creating Badges in Flutter Using Flutter’s Built-in Widgets

Firstly we will create a badge using Flutter’s built-in Badge widget. In this example, we create a badge that will hold the quantity of the items the user selected. Which is common in most shopping applications.

Using the Badge widget

The Badge widget is the most straightforward approach to create badges in Flutter, but it might miss the flexibility you need.

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Badge Demo'),
          actions: const [
            Padding(
              padding: EdgeInsets.only(right: 8.0),
              child: Badge(
                label: Text('8'),
                largeSize: 20,
                textStyle: TextStyle(fontSize: 16),
                child: Icon(Icons.shopping_cart, size: 40),
              ),
            ),
          ],
        ),
        body: const SizedBox(),
      ),
    );
  }
}

In this code example, we built a badge using Flutter’s Badge widget. We enlarged the badge to 20 using the largeSize property. The label property displays the item’s quantity, which would be dynamic in a real application.

To make the quantity stand out, we increased the font size to 16 using the textStyle property. Finally, the Badge widget takes a child property, where we placed our shopping cart icon.

At last, we wrapped the Badge widget with the Padding widget to make sure it is positioned correctly in the actions property of the AppBar.

This simple approach might be enough for you to create badges in Flutter. However, there is an alternative approach that requires more code but could give you more flexibility using Flutter’s built-in widgets. If this is what you need please check out the Using the Stack and Positioned Widgets section.

If you want badges that react when you tap them, animations when the amount changes, and so on. While this can be achieved using Flutter’s built-in widgets, I recommend you check out Using the Badges Package section.

Using the Stack and Positioned Widgets

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Badge Demo'),
          actions: [
            Stack(
              alignment: Alignment.topRight,
              children: [
                const SizedBox(
                  width: 50,
                  height: 50,
                  child: Icon(Icons.shopping_cart, size: 40),
                ),
                Positioned(
                  top: -7,
                  right: 2,
                  child: Container(
                    padding: const EdgeInsets.all(6),
                    decoration: const BoxDecoration(
                      color: Colors.red,
                      shape: BoxShape.circle,
                    ),
                    child: const Text(
                      '8',
                      style: TextStyle(color: Colors.white, fontSize: 16),
                    ),
                  ),
                ),
              ],
            )
          ],
        ),
        body: const SizedBox(),
      ),
    );
  }
}

In this code example, the badge is a Container widget that is placed above the Icon using the Stack and Positioned widgets. The Stack widget allows you to overlay multiple widgets on top of each other. In this case, we are using a SizedBox widget that holds a shopping cart Icon. Then, we are placing a round badge with the number 8 on top of it.

The Positioned widget places the badge at the top right corner of the shopping cart icon. The badge has a circular red background and displays the quantity in white text.

The above approach works but requires more code, you also might run into trouble when you want to make them clickable. To make this easier you can check out the next section where we go over the Badges package.

Using the Badges Package to Create Badges in Flutter

The badges package not only makes the creation of badges in Flutter simpler but also adds additional features out of the box. Before we start using the badges package to recreate the item’s quantity badge we first need to install it.

Installing Badges Package

The installation process is simple. Just execute the following command to add the Badges package to your project:

flutter pub add badges

Once the command is executed, check your pubspec.yaml file for the added dependencies. You should see the badges package included in the dependencies section, like this:

dependencies:
  badges: ^3.1.2
  flutter:
    sdk: flutter

Implementing the Badges package

With the package installed let us recreate the same example using the Badges package:

import 'package:flutter/material.dart';
import 'package:badges/badges.dart' as badges;

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Badge Demo'),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 5),
              child: badges.Badge(
                badgeStyle: const badges.BadgeStyle(badgeColor: Colors.red),
                badgeContent: const Text(
                  '8',
                  style: TextStyle(color: Colors.white, fontSize: 16),
                ),
                position: badges.BadgePosition.topEnd(top: -10, end: -4),
                child: const Icon(Icons.shopping_cart, size: 40),
              ),
            ),
          ],
        ),
        body: const SizedBox(),
      ),
    );
  }
}

In this code example, we start by importing the Badges package. Remember to import the package as badges. Otherwise, it might clash with Flutter’s built-in Badge widget.

Similar to Flutter’s native Badge widget, the Badge widget from the package also requires a child. Here, we have used it to display our shopping cart icon. Moreover, the badgeStyle property is used to set the background color of the badge.

Inside the badgeContent property, we have placed the badge’s content, which in this case is the item’s quantity of 8, with a white color and a font size of 16.

Furthermore, the position property is used to determine where the badge should be placed relative to the wrapped widget. With BadgePosition.topEnd and top: -10, end: -4, we ensure the badge is aligned to the top right corner.

Using the Badge widget from the Badges package simplifies the code while providing similar functionality as the Stack approach. At the same time, it offers a lot of customization. As you can see in the GIF below we still have a similar badge but it is already animated, which will play once the user opens the screen.

In the above example, we saw how easy it is to create flexible badges in Flutter using the Badges packages. If you are not convinced yet, here are some other great advantages of the package.

Advantages of Using the Badges Package to Create Badges in Flutter

The badges package offers the following advantages:

  1. Easy Setup: The package makes making badges easy, saving you time and making things simpler.
  2. Perfect Placement: You can precisely position badges where you want them, whether at corners, edges, or custom locations.
  3. Custom Shapes: Unlike standard circular badges, you can create badges in various shapes, matching your application style.
  4. Flexible Styling: Customize badge colors, text styles, and padding to integrate with your application design.
  5. Engaging Animation: The package offers built-in animations, making badges more engaging and interactive.
  6. Clickable Badges: The onTap property makes it very easy to add user actions when the badge is tapped.

Conclusion

In this post, we explored two methods for making badges in Flutter. We started by creating badges using Flutter’s built-in widgets like the Badge widget and the combination of the Stack and Positioned widgets. After that, we looked into the badges package. The Badges package is great if you want advanced badges. However, if you want a simple badge the first provided method could be enough.

If you liked this article you might be interested in reading: Create Dynamic Dropdown Buttons in Flutter

Tijn van den Eijnde
Tijn van den Eijnde
Articles: 89

Leave a Reply

Your email address will not be published. Required fields are marked *