Dart Function Optional Positional Parameters

Dart Function Optional Positional Parameters

·

1 min read

Optional Positional Parameters

  • Wrapping a set of function parameters in [] marks them as optional positional parameters. If you don't provide a default value, their types must be nullable as their default value will be null:

  •     String say(String from, String msg, [String? device]) {
          var result = '$from says $msg';
          if (device != null) {
            result = '$result with a $device';
          }
          return result;
        }
    

Default Optional Positional Parameters

  • To define a default value for an optional positional parameter besides null, use = to specify a default value. The specified value must be a compile-time constant.

  •   String say(String from, String msg, [String device = 'carrier pigeon']) {
        var result = '$from says $msg with a $device';
        return result;
      }
    
      assert(say('Bob', 'Howdy') == 'Bob says Howdy with a carrier pigeon');