Skip to main content
A redirecting constructor delegates the initialization of an instance to another constructor within the same class. It utilizes the this keyword in the initializer list to forward arguments to a target constructor, ensuring that the target constructor executes the actual initialization logic.

Syntax

The syntax requires the use of a colon : followed by this referencing the target constructor.
class ClassName {
  // Target constructor (Generative)
  ClassName(int x, int y) { ... }

  // Redirecting constructor
  ClassName.redirecting(int x) : this(x, 0);
}

Technical Constraints and Behavior

  1. No Body: A redirecting constructor cannot have a function body. The declaration must end with a semicolon immediately after the redirection call.
  2. Initializer List Exclusivity: The call to this(...) must be the only entry in the initializer list. It cannot be combined with field assignments, assertions, or calls to super.
  3. Argument Forwarding: The redirecting constructor accepts parameters defined in its signature and passes them (potentially modified or supplemented with literals) to the target constructor.
  4. Circular Dependency: Dart prevents circular redirection. Constructor A cannot redirect to Constructor B if Constructor B eventually redirects back to Constructor A.

Implementation Example

The following example demonstrates a class Automobile with a generative constructor and two redirecting constructors that forward specific arguments to the main constructor.
class Automobile {
  String make;
  String model;
  int year;

  // The main generative constructor
  Automobile(this.make, this.model, this.year);

  // Redirecting constructor 1: Forwards to the unnamed constructor
  Automobile.currentYear(String make, String model) 
      : this(make, model, DateTime.now().year);

  // Redirecting constructor 2: Forwards to the unnamed constructor with literals
  Automobile.genericSedan() 
      : this('Generic', 'Sedan', 2024);
}

void main() {
  // Instantiation triggers the redirect, which calls the main constructor
  var car = Automobile.genericSedan();
  
  print(car.make); // Output: Generic
}
Master Dart with Deep Grasping Methodology!Learn More