DEV Community

Saina
Saina

Posted on

1

Default Constructor and Named Constructor in Dart

//default consturctor

void main() {
  Book b = Book("a", "henry");
  var detail = b.deed();
  print(detail);
}

class Book {
  String? title;
  String? author;
  int? year;

  Book(this.title, this.author);
  String deed() {
    return ("${this.title}, ${this.author}");
  }
}
Enter fullscreen mode Exit fullscreen mode

//named

void main() {
  Book b2 = Book.published("Sd", "ds", 2000);
  var detail = b2.deed();
  print(detail);
}

class Book {
  String? title;
  String? author;
  int? year;
  Book.published(this.author, this.title, this.year);
  String deed() {
    return ("${this.title},${this.author},${this.year}");
  }
}
Enter fullscreen mode Exit fullscreen mode

Named constructors in Dart are used alongside default constructors to offer additional flexibility and clarity in object instantiation. While the default constructor provides a standard way to create objects, named constructors allow developers to define alternative initialization methods or configurations. This can enhance code readability, making it clear and organized. Named constructors are especially useful for scenarios where different sets of parameters or unique initialization logic are required. They can also be employed in factory patterns, providing a concise way to delegate object creation responsibilities to dedicated methods. Overall, named constructors contribute to code maintainability and expressiveness, offering developers multiple avenues for creating instances of a class with specific attributes or behaviors.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs