Home > Net >  Check if item is empty then show Icon button or nothing in flutter
Check if item is empty then show Icon button or nothing in flutter

Time:07-25

I have checked other questions but I have not seen anything which helps me understand what I need to achieve, I have a json file which populates the ListTile, but I do not want to have the IconButton show if the skills display is empty. My code does what I want it to do but it displays icons on every tile and I only want it to display if it has a link. ListTile view

Please help as I know this is an easy fix and I cannot get my head around it. Thank you

   return ListTile(
       leading: CircleAvatar(child: Text(skill.skill_id)),
          title: Text(skill.skill_name),
          subtitle: Text(skill.skill_type),
            trailing:IconButton(
             onPressed: () {
               if(skill.skill_disp.isNotEmpty)
              launchUrl(Uri.parse(skill.skill_disp));
            },
            icon: Icon(CupertinoIcons.videocam_circle),
          ),
        );

CodePudding user response:

    return ListTile(
      leading: CircleAvatar(child: Text(skill.skill_id)),
      title: Text(skill.skill_name),
      subtitle: Text(skill.skill_type),
      trailing: skill.skill_disp.isEmpty 
        ? Container()
        : IconButton(
          onPressed: () {
            if(skill.skill_disp.isNotEmpty)
              launchUrl(Uri.parse(skill.skill_disp));
          },
          icon: Icon(CupertinoIcons.videocam_circle),
      ),
    );

CodePudding user response:

This would do what you described:

   return ListTile(
       leading: CircleAvatar(child: Text(skill.skill_id)),
          title: Text(skill.skill_name),
          subtitle: Text(skill.skill_type),
            trailing:skill.skill_disp.isNotEmpty?IconButton(
             onPressed: () {
               if(skill.skill_disp.isNotEmpty)
              launchUrl(Uri.parse(skill.skill_disp));
            },
            icon: Icon(CupertinoIcons.videocam_circle),
          ):Container(),
        );

CodePudding user response:

return ListTile(
  leading: CircleAvatar(child: Text(skill.skill_id)),
  title: Text(skill.skill_name),
  subtitle: Text(skill.skill_type),
  trailing: skill.skill_disp.isEmpty 
    ? null
    : IconButton(
      onPressed: () {
        if(skill.skill_disp.isNotEmpty)
          launchUrl(Uri.parse(skill.skill_disp));
      },
      icon: Icon(CupertinoIcons.videocam_circle),
  ),
);

more better.

 return ListTile(
      leading: CircleAvatar(child: Text(skill.skill_id)),
      title: Text(skill.skill_name),
      subtitle: Text(skill.skill_type),
      trailing:IconButton(
          onPressed: skill.skill_disp.isEmpty 
                     ? null
                     : () {
                  if(skill.skill_disp.isNotEmpty)
                     launchUrl(Uri.parse(skill.skill_disp));
                  },
          icon: Icon(CupertinoIcons.videocam_circle),
      ),
    );

I hope it could help.

  • Related