Optional Parameters
- Optional Positional argument:
- Optional Named Argument:
- Optional Parameters with default values:
In normal case, you have to specify all parameters value when you declare a function with arguments, then. But what we will do if we want our arguments to be optional.
You are free to give value to optional parameters or not. If you don’t specify its value then also its okay.
Good practice says optional parameters should be placed in last at parameters list.
Wrapping a set of function parameters in [] marks them as optional positional parameters:
void main() {
void say(String msg1, [String msg2, String msg3]) {
print(msg1);
if (msg2 != null) print(msg2);
if (msg3 != null) print(msg3);
}
say("hi");
print("----");
say("hi", "salut");
print("----");
say("hi", "salut", "Hallo");
}
----
hi
salut
----
hi
salut
Hallo
In optional positional argument if we don’t pass value then it is set to NULL.
For Optional Named Parameter, the parameter's name must be specified while the value is being passed. A parameter wrapped by { } is a named optional parameter. Here is an example:
void main() {
void say(String msg1, {String msg2, String msg3}) {
print(msg1);
if (msg2 != null) print(msg2);
if (msg3 != null) print(msg3);
}
say("hi");
print("----");
say("hi", msg3: "hallo");
print("----");
say("hi", msg2: "salut", msg3: "Hallo");
print("----");
say("hi", msg3: "hallo", msg2: "salut");
}
----
hi
hallo
----
hi
salut
Hallo
----
hi
salut
hallo
The advantage here is that as we specify the parameter's name and value, we can pass parameters in any order.
In optional positional Parameters and optional named Parameters, if you don’t specify the value at function calling it will set to NULL.
Your function can use = to define default values for both named and positional parameters. The default values must be compile-time constants. If no default value is provided, the default value is null.
void main() {
void say1(int value1, {int value2 = 0, int value3 = 0}) {
print("value1:$value1 value2:$value2 value3:$value3");
}
void say2(msg1, [msg2 = "empty", msg3 = "empty"]) {
print("msg1:$msg1 msg2:$msg2 msg3:$msg3");
}
say1(4, value3: 5);
say2("one", "two");
}
msg1:one msg2:two msg3:empty