In this guide, we will learn how to implement the Counter Badge in Flutter by using the external package name badges. The counter badge is very necessary for cart buttons, inbox buttons, and orders like UIThe counter badge is very necessary on cart buttons, inbox buttons, and orders like UI. Badges can be created using the Badge() widget.
Properties of Badge Widget
badgeContent | content of badge. Usually Text or Icon . |
badgeColor | The background color of the badge. |
child | main widget. By default, it’s below the red badge. Usually Icon , IconButton , Text or button. |
elevation | Shadow of the badge. |
gradient | Gradient color for the badge content. |
toAnimate | Whether animate badge when badge content changed or not. |
position | Allows to set custom position of [badgeContent]. according to [child]. |
shape | the shape of the badge either square or circle |
alignment | Alignment of the whole widget |
showBadge | Hide or show a badge with animation using the bool flag. |
animationType | Can be one of BadgeAnimationType.slide , BadgeAnimationType.scale or BadgeAnimationType.fade . |
animationDuration | The duration of badge animation when badge content is changed. |
Installing:
In your pubspec.yaml
dependencies:
badges: ^2.0.3
import 'package:badges/badges.dart';
Let’s take an example of how we can implement the badge in our flutter application.
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
class BadgeScreen extends StatefulWidget {
const BadgeScreen({Key? key}) : super(key: key);
@override
State<BadgeScreen> createState() => _BadgeScreenState();
}
class _BadgeScreenState extends State<BadgeScreen> {
int counter = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Badge in Flutter'),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
counter++;
});
},
child: const Icon(Icons.add),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Badge(
badgeColor: Colors.lightBlueAccent,
borderRadius: BorderRadius.circular(20),
padding: const EdgeInsets.all(4),
shape: BadgeShape.square,
badgeContent: Text(counter.toString()),
animationType: BadgeAnimationType.slide,
toAnimate: true,
child: const Icon(
Icons.shopping_cart,
size: 50,
)),
),
],
),
);
}
}
Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below:
Get the full snippet from here