Dart Functions: Optional Positional Parameters

Dart Functions: Optional Positional Parameters

Positional optional parameters are declared inside square brackets [ ] and are identified by their position in the arguments list.

When calling the function, these parameters can be omitted.

void functionName(parameter1 ,[parameter2, parameter3, ...]) {
  // Function body
}

In the case of optional positional parameters, if a value is not passes then it will be assigned a default value of null.

  • Line 1: The function is defined with two parameters: name of type String and message of type String (optional positional), and check that message parameter is null?

  • Line 2: Inside the function an if statement is used to check if the message parameter is not null.

  • Line 3: If the message is not null, it means a value was provided when calling the function, so it prints the concatenated string of message, followed by a comma and the name.

  • Line 5: If the message is null, which means no value was provided for message, so it prints a generic greeting of "Hello" followed by the name.

  • Line 10: Only the name argument is provided in the first function call function('Alice'), and the message argument is omitted. Therefore, the function prints Hello, Alice! as the default greeting.

  • Line 11: In the second function call function('Bob', 'Good morning'), name and message arguments are provided. The function recognizes the provided message value as Good morning and prints Good morning, Bob!.