skip to Main Content

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

Answers


  1. 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
        ))
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search