Optional Parameters in Dart Programming


Optional parameters are those parameters that don't need to be specified when calling the function. Optional parameters allow us to pass default values to parameters that we define. There are two types of optional parameters, mainly −

  • Ordered (positional) optional parameters

  • Named optional parameters

Ordered Optional Parameters

Ordered optional parameters are those parameters that are wrapped in [ ]. For example,

void printSomething(int a, int b, [ int c = 10] ){
   // function body
}

They give us the freedom to call the function with or without the third parameter.

Example

Consider the example shown below −

 Live Demo

void printSomething(int a, int b, [ int c = 99]){
   print(a + b + c);
}
void main(){
   printSomething(2,3);
   printSomething(2,3,5);
}

In the above example, we can notice easily that when we invoke the printSomething() function for the first time we are not passing any argument, and the next time we invoke the function we are passing 5 as an argument to the third parameter of the printSomething() function.

Output

104
10

Named Optional Parameters

A parameter wrapped by { } is a named optional parameter. Also, it is necessary for you to use the name of the parameter if you want to pass your argument.

Example

Consider the example shown below −

void printSomething(int a, int b, {int c = 99}){
   print(a + b + c);
}
void main(){
   printSomething(2,3);
   printSomething(2,3,c : 10);
}

Notice that when invoking the printSomething function for the second time we wrote the name of the parameter c, followed by a colon and the value that we want to pass an argument.

Output

104
15

We can also have multiple named optional parameters too.

Example

Consider the example shown below −

void printSomething(int a, int b, {int c = 99, int d = 100}){
   print(a + b + c + d);
}
void main(){
   printSomething(2,3,c : 10);
   printSomething(2,3,c : 10 , d : 11);
}

Output

115
26

Updated on: 24-May-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements