Dart (Flutter) constructor types

Prabhanu Gunaweera
2 min readMar 5, 2023

In this article, I will discuss constructor types in Dart (the programming language used in the Flutter framework). My main objectives in writing this article are to give a basic idea about all constructor types in Dart and show the code implementation of those constructors.

Constructor types in dart;

  • Default constructor
  • Named constructor
  • Factory constructor
  • Redirecting constructor
  • Constant constructor
  • Private constructor

Let's look at them one by one

Default constructor

This is a constructor with no parameters and hence it is also called the no-arg constructor. This is created automatically by the Dart compiler when there is no constructor in the class.

Named constructor

The named constructor is a constructor that creates with a name. it is possible to create as many named constructors for a class. The named constructors are important when creating an object of a class in some specified way, like creating an object using a JSON object.

Factory constructor

The factory constructor returns a new instance of a class. The difference between this constructor and other constructors is that this constructor can also return instances of its subclass types.

Redirecting constructor

The redirecting constructor is a constructor that calls another constructor of the same class. Especially, using this type of constructor can improve reusability and readability as well as the reliability of the code.

Constant constructor

The constant constructor makes class variables unmodified and needs to make all the class variables final when implementing this. This can be used when implementing immutable objects and this improves the performance of applications as the Dart compiler optimizes objects created using a constant constructor.

Private constructor

The private constructor is a constructor that can only be accessed within its class. This is important in situations like implementing the singleton pattern.

It is very important to have a clear understanding of the different types of constructors to use them in the right places in your code, which improves code readability and reliability at the same time.

I hope this article helps you to get a clear idea about the Dart constructors. Thanks for reading.

Happy debugging..!

--

--

Prabhanu Gunaweera

Engineer | Developer | Tech blogger | Flutter consultant