Is there an easier (and cleaner) way to pass an optional parameter from one function to another than doing this:
void optional1({num x, num y}) {
if (?x && ?y) {
optional2(x: x, y: y);
} else if (?x) {
optional2(x: x);
} else if (?y) {
optional2(y: y);
} else {
optional2();
}
}
void optional2({num x : 1, num y : 1}) {
...
}
The one I actually want to call is:
void drawImage(canvas_OR_image_OR_video, num sx_OR_x, num sy_OR_y, [num sw_OR_width, num height_OR_sh, num dx, num dy, num dw, num dh])
At least I don’t get a combinatorial explosion for positional optional parameters but I’d still like to have something simpler than lot’s of if-else.
I have some code that uses the solution proposed in the first answer (propagating default values of named optional parameters, but I lose the ability to check whether or not the value was provided by the initial caller).
I’ve been burned by this corner of Dart several times. My current guidelines, which I encourage anyone to adopt are:
nulland check for that in the body of the function. Document what value will be used ifnullis passed.?argument test operator. Instead, just test fornull.This makes not passing an argument and explicitly passing
nullexactly equivalent, which means you can always forward by explicitly passing an argument.So the above would become:
I think this pattern is cleaner and easier to maintain that using default values and avoids the nasty combinatorial explosion when you need forward. It also avoids duplicating default values when you override a method or implement an interface with optional parameters.
However, there is one corner of the Dart world where this doesn’t work: the DOM. The
?operator was designed specifically to address the fact that there are some JavaScript DOM methods where passingnullis different from passingundefined(i.e. not passing anything).If you’re trying to forward to a DOM method in Dart that internally uses
?then you will have to deal with the combinatorial explosion. I personally hope we can just fix those APIs.But if you’re just writing your own Dart code, I really encourage you to avoid default values and
?entirely. Your users will thank you for it.