Flutter: Conditional statement for my IconButton is not working

61 views Asked by At

I only want my iconButton to show if there is more info on my row. What is the correct way to code this? My if has red error mark on it.

                  if(item.info != ""){
                          child: IconButton(
                          icon:
                          const Icon(Icons.info_outline_rounded),
                               onPressed: () {
                      
                                 Navigator.push(
                                   context,
                                   MaterialPageRoute(
                                   builder: (context) => const Page2()));
                               }, //onPressed
                          ), //IconButton
                 }, //end if statement
     ), //Center
2

There are 2 answers

1
Sartaj Roshan On BEST ANSWER
Center(
  child: item.info != ""
      ? IconButton(
          icon: const Icon(Icons.info_outline_rounded),
          onPressed: () {
            Navigator.push(context,
                MaterialPageRoute(builder: (context) => const Page2()));
          }, //onPressed
        )
      : Container(),
)

or with Visibility widget

Visibility(
    visible: item.info != "",
    child: IconButton(
      icon: const Icon(Icons.info_outline_rounded),
      onPressed: () {
        Navigator.push(context,
            MaterialPageRoute(builder: (context) => const Page2()));
      }, //onPressed
    ))
0
Harsh Sureja On

And if you do not want to add unnecessary widget while condition is false. You can try this

if (item.info != "")
              Center(
                  child: IconButton(
                icon: const Icon(Icons.info_outline_rounded),
                onPressed: () {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => const Page2()));
                }, //onPressed
              )),

If condition will false then it will not render any widget.