Default Constructor and Named Constructor in Dart

Saina - Jan 15 - - Dev Community

//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.

. . . . . . .