Search code examples
flutterdartdynamicwidgetchildren

how to change the icon when have no children in flutter widget?


Notification Case Senerio

IconButton(
            onPressed: () {
              Navigator.pushNamed(context, Routes.notification);
            },
            icon: ImageIcon(
              Notification == null ? AssetImage("../../images/Icons/bell.png")  : AssetImage("../../images/Icons/bin.png"),
              size: 21,
            ),
          ),

What i wanted is to change the icon whenever any specific widget contains 0 children

My Idea is to change the notification icon when we have zero notification and use another icon when notification widget have same children or have some notification


Solution

  • make a list of notification, when length of children was empty,

    I suggest to use badges package:

      final List _notifications = ['hello'];
    
      @override
      Widget build(BuildContext context) {
        return Center(
          child: Badge(
            badgeContent: _notifications.isEmpty
                ? null
                : Text(_notifications.length.toString()),
            child: _notifications.isEmpty
                ? const Icon(Icons.notifications)
                : const Icon(Icons.notifications_active),
          ),
        );
      }
    

    result

    now just add items to your List in StatefulWidget by setState and do what you like, if you need IconButton just pass it in child of your Badge,

    read badges doc to fix badgeContent, good luck