简体   繁体   中英

Pass only the specified optional params to an underlying widget

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?

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
      )
}

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, ie, stating that height and width are double .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM