Skip to main content
Positional parameters are function parameters where the mapping between the argument provided at the call site and the parameter defined in the function signature is determined solely by the index of the argument in the list.

Required Positional Parameters

By default, positional parameters are mandatory. The caller must provide an argument for every parameter declared, matching the exact order and type defined in the function signature. Syntax:
returnType functionName(Type param1, Type param2) {
  // Function body
}
Invocation:
void add(int a, int b) {
  print(a + b);
}

// Valid
add(10, 5); // a is 10, b is 5

// Invalid: Too few arguments
// add(10); 

// Invalid: Wrong order (if types differ)
// add("string", 10); 

Optional Positional Parameters

Dart supports optional positional parameters by wrapping them in square brackets []. These parameters may be omitted during function invocation. Constraints:
  1. Optional positional parameters must occur after all required positional parameters.
  2. A function cannot define both optional positional parameters and named parameters.
Syntax:
returnType functionName(Type required1, [Type? optional1, Type? optional2]) {
  // Function body
}
Invocation:
void log(String message, [String? priority, String? device]) {
  print('$message - $priority - $device');
}

// Valid: Only required
log('Error'); 

// Valid: Required + first optional
log('Error', 'High'); 

// Valid: All parameters
log('Error', 'High', 'Mobile');

// Invalid: Skipping the middle positional parameter
// log('Error', , 'Mobile'); 

Default Parameter Values

Optional positional parameters can be assigned a default value using the = operator. If the caller omits the argument, the parameter is initialized with the default value. If no default is provided and the type is nullable, the value defaults to null. Rules:
  • The default value must be a compile-time constant.
  • Non-nullable optional parameters must have a default value.
Syntax:
void connect([String host = 'localhost', int port = 8080]) {
  print('Connecting to $host:$port');
}
Invocation:
// Uses defaults: host='localhost', port=8080
connect(); 

// Overrides first: host='127.0.0.1', port=8080
connect('127.0.0.1'); 

// Overrides both: host='127.0.0.1', port=3000
connect('127.0.0.1', 3000); 
Master Dart with Deep Grasping Methodology!Learn More