Dart Optional Parameters
Dart functions can have optional parameters with default values. When we create a function, we can specify parameters that calling code can provide; but if the calling code chooses not to, the function uses the default values.
There are some important points to remembers :
- We can use optional parameters in methods and constructors.
- Every optional parameter contains a default value which is the part of its definition.
- When no value is passed to the optional arguments in the parameter, then it takes its default value.
- When a value is passed to the optional argument, the value passed by the user is considered over the default value.
- The optional parameters are always defined at the end of the parameter list.
- Provide a value for each optional parameter in the order in which they are declared, reading from left to right. The calling code can provide arguments to populate each of the optional parameters. Any parameters not populated default to null or the specified default value.
Optional parameters must appear in a block together after all positional parameters are defined. The optional parameters block is defined within a pair of curly brackets and is a comma-separated list.
func( int a, { int b : 5, int c : 6, int d : 7 } )
The default values for optional names parameters use a colon ( : ) to separate the parameters name and value. We can now call this function passing in the mandatory argument as following :
func( 5, b : 10, c : 11, d : 12 ) ;
func( 5, b : 10, c : 11 ) ;
func( 5, b : 10 ) ;
The calling statement must specify the parameter name for all supplied optional parameter values. The following statement is invalid :
func( 5 , 1, 11 ) ;
Consider the following code that explains the concept of optional parameters :
Example 1 :
void main( )
{
print( " This is the code for optional parameters : " ) ;
// calling the functions with different values being passed in parameters
print( " \n First function call : \n " ) ;
func( 1, b : 2 , c : 3) ;
print( " \n Second function call : \n " ) ;
func( 1, b : 2 ) ;
print( " \n Third function call : \n " ) ;
func( 1, c : 3 ) ;
print( " \n Fourth function call : \n " ) ;
func( 1 ) ;
}
// function definition with optional parameters
void func(int a, { int b = 5, int c = 6 } )
{
print( " The value of a is : $a " ) ;
print( " The value of b is : $b " ) ;
print( " The value of c is : $c " ) ;
}
Output :
First function call :
The value of a is : 1
The value of b is : 2
The value of c is : 3
Second function call :
The value of a is : 1
The value of b is : 2
The value of c is : 6
Third function call :
The value of a is : 1
The value of b is : 5
The value of c is : 3
Fourth function call :
The value of a is : 1
The value of b is : 5
The value of c is : 6