Dart supports both named optional parameters and positional optional parameters. What are the differences between the two?
Also, how can you tell if an optional parameter was actually specified?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Dart has two types of optional parameters: named and positional. Before I discuss the differences, let me first discuss the similarities.
Dart’s optional parameters are optional in that the caller isn’t required to specify a value for the parameter when calling the function.
Optional parameters can only be declared after any required parameters.
Optional parameters can have a default value, which is used when a caller does not specify a value.
Positional optional parameters
A parameter wrapped by
[ ]is a positional optional parameter. Here is an example:In the above code,
portis optional and has a default value of80.You can call
getHttpUrlwith or without the third parameter.You can specify multiple positional parameters for a function:
The optional parameters are positional in that you can’t omit
portif you want to specifynumRetries.Of course, unless you know what 8080 and 5 are, it’s hard to tell what those apparently magic numbers are. You can use named optional parameters to create more readable APIs.
Named optional parameters
A parameter wrapped by
{ }is a named optional parameter. Here is an example:You can call
getHttpUrlwith or without the third parameter. You must use the parameter name when calling the function.You can specify multiple named parameters for a function:
Because named parameters are referenced by name, they can be used in an order different from their declaration.
I believe named parameters make for easier-to-understand call sites, especially when there are boolean flags or out-of-context numbers.
Checking if optional parameter was provided
Unfortunately, you cannot distinguish between the cases “an optional parameter was not provided” and “an optional parameter was provided with the default value”.
Note: You may use positional optional parameters or named optional parameters, but not both in the same function or method. The following is not allowed.