Skip to main content
A default parameter in Dart is a compile-time constant expression assigned to an optional parameter. The Dart compiler substitutes this constant value into the function’s execution context when the caller omits the corresponding argument during invocation. Default parameters can be applied to both named optional parameters (enclosed in curly braces) and positional optional parameters (enclosed in []). They cannot be applied to mandatory parameters.

Syntax and Mechanics

The assignment operator (=) is used to declare a default value.

Named Optional Parameters

When defining named parameters, the default value is specified directly after the parameter declaration.
void configureNetwork({String protocol = 'https', int timeout = 3000}) {
  print('$protocol, $timeout');
}

// Invocation
configureNetwork(); // Uses 'https' and 3000
configureNetwork(timeout: 5000); // Uses 'https' and 5000

Positional Optional Parameters

For positional parameters, the default value is assigned within the square brackets. Positional optional parameters must appear after all required positional parameters.
void executeProcess(String command, [int exitCode = 0, bool force = false]) {
  print('$command, $exitCode, $force');
}

// Invocation
executeProcess('terminate'); // Uses 0 and false
executeProcess('terminate', 1); // Uses 1 and false

Technical Constraints

  1. Compile-Time Constants: Default values must be compile-time constants. You cannot use variables, instance properties, or function calls evaluated at runtime as default values.
    // INVALID: DateTime.now() is evaluated at runtime
    void logEvent({DateTime timestamp = DateTime.now()}) {} 
    
    // VALID: 'default_event' is a string literal (compile-time constant)
    void logEvent({String eventName = 'default_event'}) {}
    
  2. Implicit Null Default: If an optional parameter is declared without a default value, its implicit default is null. Consequently, the parameter’s type signature must be explicitly nullable (using the ? suffix) to satisfy Dart’s sound null safety.
    // 'port' defaults to null, so it must be typed as int?
    void initializeServer({int? port}) {}
    
  3. Collection Defaults: When providing a default value that is a collection (like a List, Set, or Map), the collection literal must be explicitly marked as const to satisfy the compile-time constant requirement.
    void applyFilters({List<String> filters = const ['all', 'active']}) {}
    
  4. Mutual Exclusivity with required: A named parameter cannot simultaneously possess a default value and the required modifier. The required keyword mandates that the caller provides an argument, rendering a fallback default value logically dead code.
    // INVALID: Cannot be both required and have a default
    void setThreshold({required int level = 10}) {}
    
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More