Dart: Redirecting Constructor

Dart: Redirecting Constructor

Sometimes a constructor's only purpose is to redirect to another constructor in the same class.

In simple words, inside in class when a constructor calls another constructor within the same class, we refer to this process as a Redirecting Constructor.

A redirecting constructor's body is empty with the constructor call appearing after a colon (:).

class Display{

    Display(this.x, this.y);//parameterized constructor
    Display.re_const(): this(2, 4);//named constructor

  • Display.named() : this(10, 20); is a redirecting constructor named named.

  • It doesn't take any parameters.

  • It redirects the construction process to the primary constructor by using constructor delegation this(10, 20).

  • When an object is created using this constructor, it immediately redirects to the primary constructor with values 10 and 20 for x and y, respectively.