badges 1.1.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 99

Badges for Flutter #

pub package

Installing: #

In your pubspec.yaml

dependencies:
  badges: ^1.1.1
import 'package:badges/badges.dart';

Basic Usage: #

    Badge(
      badgeContent: Text('3'),
      child: Icon(Icons.settings),
    )


Animations: #

BadgeAnimationType.slideBadgeAnimationType.scaleBadgeAnimationType.fade

Chips: #

Sometimes you may want to use chip but it's too big, even if set padding to zero. This is where Badge comes handy.

    Chip(
      backgroundColor: Colors.deepPurple,
      padding: EdgeInsets.all(0),
      label: Text('BADGE', style: TextStyle(color: Colors.white)),
    ),
    Badge(
      badgeColor: Colors.deepPurple,
      shape: BadgeShape.square,
      borderRadius: 20,
      toAnimate: false,
      badgeContent:
          Text('BADGE', style: TextStyle(color: Colors.white)),
    ),

Custom Usage #

There are several options that allow for more control:

PropertiesDescription
Widget badgeContentThe content of badge. Usually Text or Icon.
Color badgeColorBackground color of the badge.
Widget childThe main widget. By default it's below the red badge. Usually Icon, IconButton, Text or button.
double elevationShadow of the badge.
bool toAnimateWhether animate badge when badge content changed or not.
BadgePosition positionCan be one of BadgePosition.topLeft(), BadgePosition.topRight(), BadgePosition.bottomLeft(), BadgePosition.bottomRight(). Sometimes you want to create unique badge position or create new one manually. For this use BadgePosition.topRight(top: -12, right: -20) or BadgePosition.(left, top, right, bottom).
BadgeShape shapeBadgeShape.circle or BadgeShape.square. You can use borderRadius to change border radius of badge of you use square BadgeShape.square.
double borderRadiusBorder radius of badge. Applies only if BadgeShape.square is used.
EdgeInsets paddingThe padding of badge content.
Duration animationDurationThe duration of badge animation when badge content is changed.
BadgeAnimationType animationTypeCan be one of BadgeAnimationType.slide, BadgeAnimationType.scale or BadgeAnimationType.fade.
bool showBadgeHide or show badge with animation using bool flag.
Alignment alignmentAlignment of the whole widget


License #

This project is licensed under the Apache License 2.0 - see the LICENSE file for details

[1.1.1] - [February 27, 2020] #

  • Add alignment parameter to define position of the whole widget

[1.1.0] - [July 2, 2019] #

  • Added showBadge parameter to hide or show badge with animation

[1.0.3] - [June 5, 2019] #

  • Fixed a bug when all the badges on the screen are animated if one of them is updated. Fixed only for badges that have Text or Icon in badge content.

[1.0.2] - [June 5, 2019] #

  • Updated versions in readme.

[1.0.1] - [June 4, 2019] #

  • Updated readme images and lib description.

[1.0.0] - [June 4, 2019] #

  • Badge class for creating badges for every widget.

example/lib/main.dart

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: _buildTheme(),
      home: HomeScreen(),
    );
  }
}

ThemeData _buildTheme() {
  final ThemeData base = ThemeData.light();
  return base.copyWith(
      primaryIconTheme: base.iconTheme.copyWith(color: Colors.black));
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int _counter = 0;
  bool showRaisedButtonBadge = true;

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        bottomNavigationBar: _bottomNavigationBar(),
        appBar: AppBar(
          leading: Badge(
            position: BadgePosition.topRight(top: 10, right: 10),
            badgeContent: null,
            child: IconButton(
              icon: Icon(Icons.menu),
              onPressed: () {},
            ),
          ),
          title: Text('Badge Demo', style: TextStyle(color: Colors.black)),
          backgroundColor: Colors.white,
          actions: <Widget>[
            _shoppingCartBadge(),
          ],
          bottom: _tabBar(),
        ),
        body: Column(
          children: <Widget>[
            _addRemoveCartButtons(),
            _textBadge(),
            _raisedButtonBadge(),
            _chipWithZeroPadding(),
            expandedBadge(),
            _badgeWithZeroPadding(),
            _listView(),
          ],
        ),
      ),
    );
  }

  Widget expandedBadge() {
    return Expanded(
      child: Center(
        child: Badge(
          badgeContent: Text('10'),
          child: Icon(Icons.person, size: 30),
        ),
      ),
    );
  }

  Widget _shoppingCartBadge() {
    return Badge(
      position: BadgePosition.topRight(top: 0, right: 3),
      animationDuration: Duration(milliseconds: 300),
      animationType: BadgeAnimationType.slide,
      badgeContent: Text(
        _counter.toString(),
        style: TextStyle(color: Colors.white),
      ),
      child: IconButton(icon: Icon(Icons.shopping_cart), onPressed: () {}),
    );
  }

  Widget _tabBar() {
    return TabBar(tabs: [
      Tab(
        icon: Badge(
          badgeColor: Colors.blue,
          badgeContent: Text(
            '3',
            style: TextStyle(color: Colors.white),
          ),
          child: Icon(Icons.account_balance_wallet, color: Colors.grey),
        ),
      ),
      Tab(
        icon: Badge(
          shape: BadgeShape.square,
          borderRadius: 5,
          position: BadgePosition.topRight(top: -12, right: -20),
          padding: EdgeInsets.all(2),
          badgeContent: Text(
            'NEW',
            style: TextStyle(
                color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold),
          ),
          child: Text(
            'MUSIC',
            style: TextStyle(color: Colors.grey[600]),
          ),
        ),
      ),
    ]);
  }

  Widget _bottomNavigationBar() {
    return BottomNavigationBar(
      items: [
        BottomNavigationBarItem(
          title: Text('Events'),
          icon: Icon(Icons.event),
        ),
        BottomNavigationBarItem(
          title: Text('Messages'),
          icon: Icon(Icons.message),
        ),
        BottomNavigationBarItem(
          title: Text('Settings'),
          icon: Badge(
            shape: BadgeShape.circle,
            borderRadius: 100,
            child: Icon(Icons.settings),
            badgeContent: Container(
              height: 5,
              width: 5,
              decoration:
                  BoxDecoration(shape: BoxShape.circle, color: Colors.white),
            ),
          ),
        ),
      ],
    );
  }

  Widget _addRemoveCartButtons() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          RaisedButton.icon(
              onPressed: () {
                setState(() {
                  _counter++;
                });
              },
              icon: Icon(Icons.add),
              label: Text('Add to cart')),
          RaisedButton.icon(
              onPressed: () {
                if (_counter > 0) {
                  setState(() {
                    _counter--;
                  });
                }
              },
              icon: Icon(Icons.remove),
              label: Text('Remove from cart')),
        ],
      ),
    );
  }

  Widget _textBadge() {
    return Padding(
      padding: const EdgeInsets.all(20),
      child: Badge(
          padding: EdgeInsets.all(6),
          badgeContent: Text(
            '!',
            style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
          ),
          child: Text('This is a text'),
          position: BadgePosition.topLeft(top: -15)),
    );
  }

  Widget _raisedButtonBadge() {
    return Badge(
      showBadge: showRaisedButtonBadge,
      padding: EdgeInsets.all(8),
      badgeColor: Colors.deepPurple,
      badgeContent: Text(
        '!',
        style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
      ),
      child: RaisedButton(
        onPressed: () {
          setState(() {
            showRaisedButtonBadge = !showRaisedButtonBadge;
          });
        },
        child: Text('Raised Button'),
      ),
    );
  }

  Widget _chipWithZeroPadding() {
    return Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
      Text('Chip with zero padding:'),
      Chip(
        label: Text('Hello'),
        padding: EdgeInsets.all(0),
      ),
    ]);
  }

  Widget _badgeWithZeroPadding() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text('Badges:'),
        for (int i = 0; i < 5; i++)
          _getExampleBadge(padding: (i * 2).toDouble())
      ],
    );
  }

  Widget _getExampleBadge({double padding}) {
    return Padding(
      padding: const EdgeInsets.all(4),
      child: Badge(
        badgeColor: Colors.lightBlueAccent,
        borderRadius: 20,
        padding: EdgeInsets.all(padding ?? 4),
        shape: BadgeShape.square,
        badgeContent: Text(
          'Hello',
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  Widget _listView() {
    Widget _listTile(String title, String value) {
      return ListTile(
        dense: true,
        title: Text(title, style: TextStyle(fontSize: 16)),
        trailing: SizedBox(
          width: 100,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Badge(
                elevation: 0,
                shape: BadgeShape.circle,
                padding: EdgeInsets.all(7),
                badgeContent: Text(
                  value,
                  style: TextStyle(color: Colors.white),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 20),
                child: Icon(
                  Icons.arrow_forward_ios,
                  size: 14,
                ),
              ),
            ],
          ),
        ),
      );
    }

    return Expanded(
      child: ListView.separated(
        itemCount: 3,
        separatorBuilder: (BuildContext context, int index) => Divider(),
        itemBuilder: (BuildContext context, int index) {
          if (index == 0) {
            return _listTile('Messages', '2');
          } else if (index == 1) {
            return _listTile('Friends', '7');
          } else if (index == 2) {
            return _listTile('Events', '!');
          }
        },
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  badges: ^1.1.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:badges/badges.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
98
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
99
Learn more about scoring.

We analyzed this package on May 24, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.1
  • pana: 0.13.8-dev
  • Flutter: 1.17.0

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.2 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test
pedantic ^1.9.0