Creating Badges in Flutter for Item Count in a Shopping Cart

Flutter Aug 18, 2023

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 better in Flutter. You will learn how to create badges using the Flutter's built-in widgets and using the badges package for an easier approach.

Creating badges

To get started we will create a badge using Flutter's built-in widgets. The badge will hold the quantity of the items the user selected. Which is common in most shopping applications. Let us go into the code:

Using Stack and Positioned

import 'package:flutter/material.dart';

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

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

In this code snippet, we create a Flutter application with an AppBar that shows a badge to highlight the item's quantities above a shopping cart icon.

The badge is positioned 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 transparent Container 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.

flutter_showcasing_shopping_cart_with_quantity_using_stack_positioned_widgets

As you can see in the GIF above we can create common badges quite easily using Flutter's built-in widgets. But we can do better.

Using the Badge widget

Flutter also includes the Badge widget, which simplifies the creation of badges by a lot:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Badge Demo'),
          actions: [
            Padding(
              padding: const EdgeInsets.only(top: 8, right: 5),
              child: Badge(
                largeSize: 20,
                label: Text('8', style: TextStyle(color: Colors.white, fontSize: 18)),
                child: Icon(Icons.shopping_cart, size: 40),
              ),
            ),
          ],
        ),
        body: SizedBox(),
      ),
    );
  }
}

In this code snippet, we created a badge using the Badge widget. We increased the size of the badge using the largeSize property and set it to 20. In the label property we added the item's quantity, set the text color to white and increased the font size to 18. The Badge widget also takes a child property, which we used to display our shopping cart icon.

At last we wrapped our Badge widget with the Padding widget to position the widget.

flutter_showcasing_shopping_cart_with_quantity_using_badge_widget

This simpler approach might be enough for you to display the right badge. However, you might 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, using the badges package can make things easier.

Using badges package

The badges package not only makes the creation of badges 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

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

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.1
  flutter:
    sdk: flutter

Implementation

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(MyApp());

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

In this code snippet, 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 since the package itself also includes a Badge widget.

Similar to Flutter's native Badge widget, the Badge widget from the package also requires a child, which we have used here to display our shopping cart icon. The badgeColor 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 18.

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

Using the Badge widget simplifies the code while providing similar functionality as the Stack approach, and it offers the advantage of customization options provided by the package.

flutter_showcasing_shopping_cart_with_quantity_using_badges_package

Advantages

The badges 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 applications style.
  4. Flexible Styling: Customize badge colors, text styles, and padding to integrate with your applications design.
  5. Engaging Animation: The package offers built-in animations, making badges more engaging and interactive.
  6. Clickable Badges: Attach onPressed actions to badges for user interaction, ideal for notifications or actions.

Conclusion

In this post, we explored two methods for making badges in Flutter. We began by using Flutter's basic widgets like Stack and Positioned, and later, we simplified the process with Flutter's own Badge widget. Additionally, we looked into the badges package and its benefits to make badge creation even simpler.

Tags