flutterdartternary-operator

Ternary Operator on badges to reveal badges only when there is a new message


might be a simple problem to solve.

I'm trying to show the badges icon on the chat screen only if there are unread messages.

The default number of badges has already been set to '0'.

How do I code the ternary operator such that it doesn't even appear if there are no unread messages, and appear only if there is at least one unread messages?

Issue I'm having, badges are appearing even when unread messages is zero (embedded in the following link):

enter image description here

 new Container(
                margin: new EdgeInsets.symmetric(horizontal: 5.0),
                child: new InkWell(
                    child: new Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                      new Badge(
                          badgeColor: Colors.green[300],
                          badgeContent: Padding(
                            padding: const EdgeInsets.only(left: 3.0, right: 3),
                            child: Text('${badges ?? ''}' == 0
                                ? ''
                                : '${badges ?? ''}'),
                          ))
                    ]))),

Solution

  • badges > 0
    ? new Container(
        margin: new EdgeInsets.symmetric(horizontal: 5.0),
        child: new InkWell(
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              new Badge(
                badgeColor: Colors.green[300],
                badgeContent: Padding(
                  padding: const EdgeInsets.only(left: 3.0, right: 3),
                  child: Text('$badges'),
                ),
              ),
            ],
          ),
        ),
      ),
    : CustomWidget() //Return what you want here
    

    You can nest the ternary operator to put the condition on deeper widgets.