Dart: Optional Parameters

# Optional Positional Parameter

void function_name(param1, [optional_param_1, optional_param_2]) { } 

If an optional parameter is not passed a value, it is set to NULL.

Example

void main() { 
   pos_param(test); 
}  
pos_param(n1,[s1]) { 
   print(n1); 
   print(s1); 
} 

It should produce the following output

test 
null 

# Optional Named Parameter

Declaring the function

void function_name(a, {optional_param1, optional_param2}) { } 

Calling the function

function_name(optional_param:value,…); 

Example

void main() { 
   test_param(i am human); 
   test_param(i am human,s1:'hello'); 
   test_param(i am human,s2:'hello',s1:'world'); 
}  
test_param(n1,{s1,s2}) { 
   print(n1); 
   print(s1); 
}  

It should produce the following output

i am human 
null 
i am human 
hello 
i am human 
world 

# Optional Parameters with Default Values

function_name(param1,{param2= default_value}) { 
   //...... 
} 

Example

void main() { 
   test_param(hello); 
}  
void test_param(n1,{s1:world}) { 
   print(n1); 
   print(s1); 
}   

=> output

hello 
world 

Leave a Reply

Your email address will not be published. Required fields are marked *