Skip to main content
An initializing formal parameter is a syntactic construct in Dart constructors that declares a parameter and automatically assigns its value to a corresponding class instance variable. Identified by the this. prefix, it performs the assignment implicitly during the initialization phase, before the constructor body executes.

Syntax

The syntax replaces the standard type and parameter name with this. followed by the name of the instance variable.
class Vector2 {
  final double x;
  double y;

  // Standard constructor syntax (verbose)
  Vector2.standard(double x, double y) : x = x, y = y;

  // Initializing formal parameter syntax (concise)
  Vector2(this.x, this.y);
}

Technical Mechanics

  1. Implicit Initialization: The parameter value is assigned to the instance variable as part of the initializer list sequence. This occurs before the constructor body runs.
  2. Type Inference: The parameter implicitly inherits the type of the instance variable it initializes. While explicit type annotation is valid (e.g., Vector2(double this.x)), it is redundant and generally omitted.
  3. Scope: The parameter name is available within the initializer list and the constructor body, shadowing the instance variable name unless this. is explicitly used in the body.

Parameter Variations

Initializing formal parameters support all standard parameter kinds: positional, named, and optional.

Positional

The argument is mapped based on its order in the call site.
class Container {
  int id;
  Container(this.id); 
}

Named

The argument is mapped by key. Named initializing parameters can be marked required or provided with default values.
class Config {
  String host;
  int port;

  Config({
    required this.host, 
    this.port = 8080
  });
}

Optional Positional

The argument is mapped by order but is not mandatory.
class Log {
  String message;
  String level;

  Log(this.message, [this.level = 'INFO']);
}

Interaction with Modifiers

  • final Fields: Because the assignment occurs during the initialization phase (not the body execution phase), initializing formal parameters are valid for initializing final fields.
  • Null Safety:
    • If the field is non-nullable, the parameter must be mandatory (positional or required named) or have a default value.
    • If the field is nullable, the parameter may be optional without a default value.
  • const Constructors: Initializing formal parameters can be used in constant constructors, provided the assignment results in a compile-time constant state.
Master Dart with Deep Grasping Methodology!Learn More