In Dart, you can set a default value for a parameter in a function definition. The default value is used if the caller does not provide a value for that parameter.
Here’s an example of a function with a default value for a parameter:
void printMessage(String message, [String sender = 'Unknown']) {
print('$sender: $message');
}
In this example, the sender
parameter has a default value of 'Unknown'
. If you call printMessage
and only provide a value for the message
parameter, the default value for sender
will be used:
printMessage('Hello');
// Output: Unknown: Hello
If you want to provide a value for sender
, you can do so when you call the function:
printMessage('Hello', 'John');
// Output: John: Hello
In this way, you can use default values for parameters to make your functions more flexible and easier to use.