In this tutorial you will learn about the Dart Optional Parameters and its application with practical example.
Dart Optional Parameters
In Dart, we are can set any parameter as optional; which allows function with optional parameter (if any) to be called/executed even if the values for those parameters is being not provided. A parameter can be set as optional by appending a question mark along with its name. Optional parameters are declared after the required parameters of a function. There are two types of optional parameter in Dart functions –
Optional Positional Parameter
Optional positional parameters can be specified by having individual parameter separated by commas and enclosed within square brackets ([]). Calling a function having optional positional parameters defined may specify a variable number of arguments.
Syntax:-
1 |
void function_name(param1, [optional_param_1, optional_param_2]) { } |
Example:-
1 2 3 4 5 6 7 8 |
void main() { print("W3Adda - Dart Optional Positional Parameter."); test_param(12); test_param(123,21); } test_param(p1,[o1]) { print("Param Value Is : ${p1} and Option Param Valus Is : ${o1}"); } |
Output:-
Optional named parameter
Named positional parameters can be specified by having individual parameter name separated by commas and enclosed within curly brackets ({ }).
Syntax:-
1 |
void function_name(param1, {optional_param1, optional_param2}) { } |
Calling a function having optional named parameters, the individual parameter’s name must be specified while the value is being passed. Names are specified using parameter:value.The sequence of passing the parameter(s) does not matter.
Syntax:-
1 |
function_name(optional_param1:value,...); |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 |
void main() { print("W3Adda - Dart Optional Named Parameter."); test_param(12); test_param(123,np1:10); test_param(123,np2:20); test_param(123,np1:10,np2:20); } test_param(p1,{np1, np2}) { print("Param Value Is : ${p1}"); print("Named Param 1 Valus Is : ${np1}"); print("Named Param 1 Valus Is : ${np2}"); } |
Output:-