Site icon TestingDocs.com

Constructor in Dart

Constructor in Dart

In this tutorial, we’ll explore the concept of Constructors in the Dart programming language. A constructor is a special function with the same name as its class. Its purpose is to initialize an object during its creation.

The constructor lets you set initial values and carry out setup tasks when creating an object. It is automatically triggered as soon as we create the class object.

Create Constructor

To create a constructor, follow this general syntax:

class DartClassName {
      // Constructor
     DartClassName() {
       // constructor body
     }

}

 

The constructor name should match the class name. For instance, if the class is called Book, then the constructor should also be named Book.

Also, note that the constructor function has no explicit return type because the constructor doesn’t return any value.

Example

Let’s examine the following example.

class Book {
late String title;
late String author;
late double price;

// default constructor
Book() {
    title = “Default Title”;
    author = “Default Author”;
    price = 0.0;
}

}

 

In this example, we have defined a constructor function Book() which is the same as the class name.

 

 

Now, we can create the book object that invokes the default constructor.

// create book object
Book bObj = new Book();

 

In Dart, there are several kinds of constructors that serve different purposes and have distinct syntax. Our upcoming lesson will delve into these various constructor types.

Dart Tutorials

Dart tutorial on this website can be found at:

https://www.testingdocs.com/dart-tutorials-for-beginners/

More information on Dart:

https://dart.dev/

Exit mobile version