Dart Functions: Default Optional Parameters

Dart Functions: Default Optional Parameters

Default optional parameters allow you to provide a default value when the parameter is not explicitly passed in the function call.

It ensures that the function works even if specific parameters are not provided.

Syntax:

void functionName(parameter1 ,{parameter2 = defaultValue2, parameter3 = defaultValue3, ...}) {
  // Function body
}

  • Lines 1–3: The function is defined with named parameters: name and message, both of type String in curly brackets {} having the default values assigned to them.

  • Line 6: No arguments are provided in the first function call function(), so name and message parameters use their respective default values. Therefore, the function prints "Hello, Guest!" as the default greeting.

  • Line 7: Only the name argument is explicitly provided using the named parameter syntax in the second function call function(name: 'Jinali'). The message argument is omitted, so it uses its default value. The function prints Hello, Alice! as the greeting.

  • Line 8: In the third function call function(message: 'Good afternoon', name: 'Moksha'), name and message arguments are explicitly provided using the named parameter syntax. The function recognizes the provided values for message and name, and prints Good afternoon, Moksha!.