How to make widget argument optional?

796 Views Asked by At

I have a function that I use to build an icon widget:

  buildIcon(IconData icon, Color color, VoidCallback onTap, {double? size}) {
    return InkWell(
      onTap: onTap,
      child: Icon(
        // set size only if argument size != null
        icon,
        color: color,
      ),
    );
  }

As you can see this function has nullable argument size. And I need this parameter to be set only if it is not equal to null. If I add a check for null, then I will have to add a default value for the size parameter of the icon widget.

Is it possible to avoid setting the size parameter of Icon widget if the function argument is null ? Please, help me.

2

There are 2 best solutions below

0
On

You can use like this:

buildIcon(IconData icon, Color color, VoidCallback onTap, {double? size = 10}) {
return InkWell(
  onTap: onTap,
  child: Icon(
    // set size only if argument size != null
    icon,
    color: color,
  ),
);

}

or:

 buildIcon(IconData icon, Color color, VoidCallback onTap, {double? size}) {
size ??= 10;
return InkWell(
  onTap: onTap,
  child: Icon(
    // set size only if argument size != null
    icon,
    color: color,
  ),
);

}

0
On

In this particular case, Icon's size parameter is already optional. If it's not defined, it will be set to 24px, like you defined your method like this:

buildIcon(IconData icon, Color color, VoidCallback onTap, {double? size}) {
    return InkWell(
      onTap: onTap,
      child: Icon(
        icon,
        size: size ?? 24,
        color: color,
      ),
    );
  }

as seen in the flutter docs:

If there is no IconTheme, or it does not specify an explicit size, then it defaults to 24.0.