Dart Default Value Parameter

When a function is called with argument, then these arguments is used as parameter values in function, but when a function is called or invoked without passing argument for any specific parameters than default parameter values been used as parameters value as per function definition..Dart allows to assign default optional values to parameters in a function. Such a function is called Dart Optional Default Parameters Function.Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values.

To understand the concept of default parameters let’s take an example. The syntax of default parameters function will look like this

int findVolume(int length, int breadth, {int height = 12}) {

 return length*breadth*height;

}

In the above code height is the named parameter and in addition, a default value of 12 has been assigned as well. Let’s explore more by invoking this function.

var result = findVolume(3, 6);

Here 3 is the value of length and the value of breath is 6. Only two parameters have been passed. What about the 3rd parameter? Well the third parameter will use the default assigned value.

The syntax to override the default parameter value is

var result = findVolume(3, 6,height:15);

On execution the height 15 will replace the default value of height which is 12.

Dart Default Parameters Example

Time to complete a default parameter example.

void main() {

 var result = findVolume(3, 6);

 print(result);

 print("");

 //Overriding the default parameter

 var result2 = findVolume(3, 6, height: 15);

 print(result2);

}

int findVolume(int length, int breadth, {int height = 12}) {

 return length * breadth * height;

}

Launch the application and the output result is following

216

270


Advertisements