Dart Optional Positional Parameters Function

0
3563
Dart Optional Positional Parameters
dart optional positional parameter function examples

Parameters in Dart functions are of two types.

Optional parameters are divided into three different categories.

haracteristics of Dart Optional Positional Parameters

  • Optional parameters should occur after the required parameters.
  • Square brackets are placed around the parameters.

This tutorial will cover Optional Positional Parameters. to understand optional parameters. Let’s print the name of favourite countries

  
void main() {
  favContries('Germany', 'Pakistan', 'Portugal');
}

void favContries(String name1, String name2, String name3) {
  print('First fav country name is $name1');
  print('Second fav country name is $name2');
  print('Third fav country name is $name3');
}

Console result is.

  
First fav country name is Germany
Second fav country name is Pakistan
Third fav country name is Portugal

It looks pretty much like the required parameter function. In the case of optional positional parameters, parameters can be skipped. Let’s skip the name of the last parameter. Square brackets cover the variable parameter.

  
void main() {
  favContries('Germany', 'Pakistan');
}

void favContries(String name1, String name2, [String name3]) {
  print('First fav country name is $name1');
  print('Second fav country name is $name2');
  print('Third fav country name is $name3');
}

Now just two arguments are passed and there is no complied time error. The result is given below. There is a null value in the result as no value is assigned to parameter name3.

  
First fav country name is Germany
Second fav country name is Pakistan
Third fav country name is null

In a similar way there can be more than one optional parameters. In this example let take last two parameters as optional

  
void main() {
  favContries('Germany');
}

void favContries(String name1, [String name2, String name3]) {
  print('First fav country name is $name1');
  print('Second fav country name is $name2');
  print('Third fav country name is $name3');
}

Here is the result values.

  
First fav country name is Germany
Second fav country name is null
Third fav country name is null

This is how optional parameters are done in Dart. Happy Coding

LEAVE A REPLY

Please enter your comment!
Please enter your name here