'How to make widget argument optional?
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.
Solution 1:[1]
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.
Solution 2:[2]
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,
),
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | smaso |
| Solution 2 | MalikSenpai |
