ref – https://stackoverflow.com/questions/13264230/what-is-the-difference-between-named-and-positional-parameters-in-dart
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.
1 2 3 |
getHttpUrl(String server, String path, [int port=80]) { // ... } |
In the above code, port
is optional and has a default value of 80
.
You can call getHttpUrl with or without the third parameter.
1 2 |
getHttpUrl('example.com', '/index.html', 8080); // port == 8080 getHttpUrl('example.com', '/index.html'); // port == 80 |
You can specify multiple positional parameters for a function:
1 2 3 |
getHttpUrl(String server, String path, [int port=80, int numRetries=3]) { // ... } |
But from a new reader perspective, it’s hard to tell what 8080 and 5 mean.
1 2 3 |
getHttpUrl('example.com', '/index.html'); getHttpUrl('example.com', '/index.html', 8080); getHttpUrl('example.com', '/index.html', 8080, 5); |
Thus, 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:
1 2 3 |
getHttpUrl(String server, String path, {int port = 80}) { // ... } |
You can call getHttpUrl with or without the third parameter. But if you do, you MUST use the parameter name when calling the function.
1 2 |
getHttpUrl('example.com', '/index.html', port: 8080); // port == 8080 getHttpUrl('example.com', '/index.html'); // port == 80 |
You can specify multiple named parameters for a function:
1 2 3 |
getHttpUrl(String server, String path, {int port = 80, int numRetries = 3}) { // ... } |
Because named parameters are referenced by name, they can be used in an order different from their declaration.
1 2 3 4 5 |
getHttpUrl('example.com', '/index.html'); getHttpUrl('example.com', '/index.html', port: 8080); getHttpUrl('example.com', '/index.html', port: 8080, numRetries: 5); getHttpUrl('example.com', '/index.html', numRetries: 5, port: 8080); getHttpUrl('example.com', '/index.html', numRetries: 5); |
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.
1 2 3 |
// not allowed thisFunctionWontWork(String foo, [String positonal], {String named}) { } |