Dart Optional Named Parameters Function

0
7222
optional named parameter function in dart
dart optional named parameter function examples

In Dart optional parameters are divided into three different categories and we have already covered other two categories.

In this tutorial, we will cover Dart Optional Named Parameters function.

Characteristics of Optional Named Parameters

  • Named Parameters help to avoid the errors if there are a large number of parameters
  • In the case of named parameters, the sequence does not matter.
  • Variable names of the named parameters should be same.

A curly bracket is placed around the named parameters. Let’s understand the syntax of named parameters function with an example code. Calculate the volume of cuboid. Here breadth and height are named parameters.

  
int findVolume(int length, {int breadth, int height}) {
  return length*breadth*height;
}

and this is how named parameter function is invoked. For the first parameter there is jus literal value but for the 2nd and 3rd parameter names are written as these two variable are named parameter in the function.

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

As mentioned before position or sequence of named parameter does not matter.

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

Breadth value will be assigned to the breadth parameter as it is recognized by its name. Time to complete the cuboid volume example.

  
void main() {
  var result=findVolume(3,breadth:6,height:9);
  print(result);
  print("");
  
  //Changing the parameter's sequence 
  var result2=findVolume(3,height:9,breadth:6);
  print(result2);
}

int findVolume(int length, {int breadth, int height}) {
  return length*breadth*height;
}

Launch the application and here is the output which is identical.

  
162

162

That is pretty much all from named parameters in Dart.

LEAVE A REPLY

Please enter your comment!
Please enter your name here