0

Assume I have a simple function that takes a URL to an svg image and returns a widget:

Widget loadImage(String url, { height, width }) {
  // Wrap URL in an SvgPicture and return
  return SvgPicture.network(url)
}

I'd like to apply the width and height params to SvgPicture only if they are defined. Something like this (though this obviously results in a syntax error):

Widget loadImage(String url, { height, width }) {
  // Wrap URL in an SvgPicture and return
  return SvgPicture.network(
    url,
    if(height) height : height, // <-- 
    if(width) width : width, // <-- 
  )
}

How do I do this?

FloatingRock
  • 6,741
  • 6
  • 42
  • 75

2 Answers2

2

If a parameter is optional, it means, it can be null. There for, the receiver function should ensure whether it is null or not.

So, you can simply use

Widget loadImage(String url, {double height,double width }) {
  return SvgPicture.network(
        url,
        height: height,
        width: width
      )
}
Darish
  • 11,032
  • 5
  • 50
  • 70
  • This would still pass the value `null` if height is not defined. Is there a way to not pass the parameter *at all* (without wrapping everything with if-statements) – FloatingRock Mar 04 '20 at 12:48
  • updated. Actually you can pass the height and width as it is. what problem are you facing? – Darish Mar 04 '20 at 12:50
  • In this particular instance, there's no issue (because a height of null is ignored). I was just wondering if there was a way to not pass `null` parameters to the underlying widget at all. – FloatingRock Mar 04 '20 at 12:52
  • since it is an optional parameter, you don't need to mind about not passing the value. Optional parameters can take null values by default. – Darish Mar 04 '20 at 12:55
0

There is no way you can not pass the parameter conditionally. If you want the SvgPicture widget to use its default height and width (if any), then you can pass null to those parameters. In this case, passing null to height and width has exactly the same effect as not using those parameters in the SvgPicture at all.

So the most readable way of doing it would be, simply:

Widget loadImage(String url, {double height, double width}) {
  return SvgPicture.network(
        url,
        height: height,
        width: width
      )
}

As a side note, I would recommend always type-annotating parameters in functions, i.e., stating that height and width are double.

drogel
  • 2,567
  • 2
  • 13
  • 22
  • 1
    If you want to have different default values you could do something like `height: height?? 42` [??](https://stackoverflow.com/questions/54031804/what-are-the-double-question-marks-in-dart) – jnnks Mar 04 '20 at 15:11