Sobes.tech
Junior

What types of constructors exist in Dart?

sobes.tech AI

Answer from AI

In Dart, the following types of constructors exist:

  • Generating Constructors: The primary type of constructors for creating class instances.
  • Named Constructors: Allow creating multiple constructors with different names for various initialization methods.
  • Factory Constructors: Can return an existing instance of a class or subclass, rather than necessarily creating a new one.
  • Redirecting Constructors: Call another constructor of the same class using the syntax : this(...).
  • (Implicit) Default constructor without arguments - automatically created if the class has no explicit constructors.

Example:

class Point {
  double x, y;

  // Generating constructor
  Point(this.x, this.y);

  // Named constructor
  Point.origin() : x = 0.0, y = 0.0;

  // Factory constructor
  factory Point.fromJson(Map<String, dynamic> json) {
    return Point(json['x'], json['y']);
  }

  // Redirecting constructor
  Point.fromList(List<double> coordinates) : this(coordinates[0], coordinates[1]);
}