Skip to main content
Coderweekend

How to create Multiple Constructors in Dart

Constructor overloading is the ability to create multiple constructors with different parameters.

For example, we have a Color class with a constructor that initialize four instance variable, red, green, blue, and alpha.

class Color {
final double red;
final double green;
final double blue;
final double alpha;

Color(
{required this.red,
required this.green,
required this.blue,
required this.alpha});
}

Let's say we want to create an overload initializer to initialize only the red value. We might come up with a new constructor like this.

Color(this.red)
: green = 0,
blue = 0,
alpha = 1;

Unfortunately, in Dart, you will get the following error.

The unnamed constructor is already defined.
Try giving one of the constructors a name.

The unnamed constructor is already defined #

In Dart, we can have one unnamed constructor, but we can have multiple named constructor.

  • Unnamed constructor, a constructor with the same name as its class.
  • Named constructors, a constructor with a name to provide extra clarity. This is a Dart way to implement multiple constructors for a class.

This is the reason why we get the error when trying to implement an overload initializer in the previous section.

How to create Multiple Constructors in Dart #

So, we can't have constructor overloading, but we can create as many named constructors as we want.

We can create a named constructor by appending a dot (.) and a name of your choice to an unnamed constructor.

Here is an example of a named constructor that initializes only the red value of the Color class.

Color.red(this.red)
: green = 0,
blue = 0,
alpha = 1;

Then, we can use it like this.

Color.red(0.5);

We can have as many named constructors as we want. Here is an example where I created two more named constructors, Color.blue(this.blue) and Color.green(this.green).

class Color {
final double red;
final double green;
final double blue;
final double alpha;

Color(
{required this.red,
required this.green,
required this.blue,
required this.alpha});

Color.red(this.red)
: green = 0,
blue = 0,
alpha = 1;

Color.blue(this.blue)
: green = 0,
red = 0,
alpha = 1;

Color.green(this.green)
: blue = 0,
red = 0,
alpha = 1;
}