Nur Rony
Polyglot Programmer, DevOps and Forever Learner

Dart: Optional Parameters

Dart: Optional Parameters

Optional parameters isn't required to specify a value for the parameter when calling the function. Optional parametes are declared after the required parameters of a function.

Dart has built-in support of optional parameters in functions. There are two types of optional parameter in Dart functions

  1. Named parameters
  2. Positional parameters

Named Optional Parameters

In Dart, Named optional parameters is defined by {} like below and do not matter the sequence of passing the parameter(s). Check the following example

void namedOptionalParameters(String domain,
        {String protocol, String path, int port}) =>
    print('\nProtocol: $protocol\nDomain: $domain\nPort: $port\nPath: $path');

main(List<String> args) {
  print('calling namedOptionalParameters:');
      port: 8080, path: '/about', protocol: 'https');
  namedOptionalParameters('', port: 80);
  namedOptionalParameters('', path: '/dart');

If you run the code then you find that it prints null for the optional parameters you are not passing. You can provide default values for them as well as follows

void namedOptionalParameters(String domain,
        {String protocol = 'https://', String path = "/dart", int port = 80}) =>
    print('\nProtocol: $protocol\nDomain: $domain\nPort: $port\nPath: $path');

Positional Optional Parameters

A parameter wrapped by [ ] is a positional optional parameter. As the name suggest you must pass the position parametes as the are defined in function declaration. Here is an example

void positionalOptionalParameters(String domain,
        [String protocol = 'https://', String path = "/dart", int port = 80]) =>
    print('\nProtocol: $protocol\nDomain: $domain\nPort: $port\nPath: $path');

main(List<String> args) {
  print('calling positionalOptionalParameters:');
  positionalOptionalParameters('', 'https', '/about', 8000);
  positionalOptionalParameters('', 'https', '/');
  positionalOptionalParameters('', 'https');

As you see there is no way to specify path without specifying protocol. Also notice how to pass the default value as well

Note: You may use positional optional parameters or named optional parameters, but not both in the same function or method.

Good Day!!