Dart Constructors : Use Default, Parameterized, and Named

Home » Dart » Dart Constructors : Use Default, Parameterized, and Named

Dart constructors are special methods used to initialize objects. In the previous examples, we learned about classes and objects in Dart. It’s super essential to understand the workings of classes and objects before delving deep into constructors in Dart.

Dart Constructors : Use Default, Parameterized,  and Named

Why should we use constructors in Dart?

Constructors are common in many modern and old programming languages. In Dart, they are commonly used for initializing or setting initial values to the properties (e.g., a Car class may have a color or model property) of an object. When you create an object of a class, the constructor is responsible for preparing the object for use by assigning initial values to its properties.

Constructors use the same names as the classes, so they don’t require any additional keyword like ‘construct’.

Student Constructor

class Student{

 Student() { //Constructor 
 }

}

The default Dart constructor

The default Dart constructor is created automatically if you don’t declare any constructor explicitly. Let’s look at an example.

class Student{
  String? name;
  
  //No constructor explicitly defined here.
}

If you observe the above code snippet, there is no explicit declaration of a constructor.

Explicit Declaration:

class Student{
  String? name;
  
  Student() {
 }

}

Using a default constructor in Dart:

Creating an object using the default constructor:

Student student= Student();

Accessing object properties:

student.name = "Nikki";

Program example:

class Student{
  String? name;
  
  //No constructor explicitly defined here.
}
void main() {

 // Creating an object using the default constructor
 Student student= Student();

 // Accessing object properties 
 student.name = "Nikki";

 print('Hello ${student.name}');



}

Output:

Hello Nikki

Parameterized Constructor

A parameterized constructor allows you to initialize object properties with values passed during the object’s creation.

Example:

Open DartPad and write the following code:

class Savings
{
  String? accountName;
  int? balanceAmount;

  Savings(String name, int amount)
  {
    accountName = name;
    balanceAmount = amount;
  }
  void getInfo() 
  {
    print('Person Name : $accountName');
    print('Person\'s Balance: $balanceAmount');
  }

}

void main() {
  Savings saving = Savings('Lakshmi',6000);
  saving.getInfo();
}

Person Name : Lakshmi
Person's Balance: 6000

Let’s use ‘this’ keyword

In Dart, the ‘this’ keyword is used to refer to the current instance of the class within its methods, including constructors.

This is especially useful when there is a naming conflict between parameters and class fields. Here’s an example to illustrate:

//using this keyword
class Demo {
  String? id;
  double? value;

  Demo(id, value){
   this.id = id;
   this.value = value;
  }
  void show() {
    print('ID : $id \n Value: $value');
  }
}
void main() {
 
  Demo demo = Demo('CVBG1', 89.00);
  demo.show();

}

Output:

Value: 89.0

Named Constructor in Dart

Named constructors, which come with distinct names, prove valuable when you wish to offer multiple methods for creating an object.

class Foo {
  String? task_name;
  
  //named constructor 
  Foo.task() {
    print("Starting task..");
  }
}

void main() {

  Foo task = Foo.task();
  task.task_name = "Sending Mail";
  print(task.task_name);
  
}

Output

Starting task..
Sending Mail

Dart Constructor with Initializer List

The initializer list enables you to establish object properties before the constructor body is executed.

class Colors 
{
  String colorCode;
  String colorName;
  //constructor with initializer list 
  Colors(String code, String name) : 
      colorName = name, colorCode = code {
      print('Constructor called..');
      print('color : $colorName, colorCode: $colorCode');
  }

}

void main() {

Colors color = Colors('#fff000', 'Light Yellow');

}

Constructor called..
color : Light Yellow, colorCode: #fff000

Congratulations! You have mastered the fundamental concepts of constructors in the Dart programming language.

You may also like...