Constructors in Dart
Constructors are special methods in Dart that are used to create and initialize objects of a class. They play a crucial role in defining how an object is set up when it is instantiated. This documentation will cover the different types of constructors in Dart, including default constructors, named constructors, factory constructors, and more.
Types of Constructors
1. Default Constructor
A default constructor is automatically provided by Dart if no constructors are defined in the class. It initializes the properties of the class with default values.
Example
class Person {
String name;
int age;
// Default constructor
Person();
}
void main() {
Person person = Person();
print('Name: ${person.name}, Age: ${person.age}'); // Output: Name: null, Age: null
}
Explanation
- Person(): This is the default constructor. If properties are not initialized, they default to
null
for non-primitive types.
2. Parameterized Constructor
A parameterized constructor allows you to initialize an object with specific values upon creation.
Example
class Person {
String name;
int age;
// Parameterized constructor Person(this.name, this.age);
}
void main() {
Person person = Person('Alice', 30);
print('Name: ${person.name}, Age: ${person.age}'); // Output: Name: Alice, Age: 30
}
Explanation
- Person(this.name, this.age): This constructor takes parameters to initialize the
name
andage
properties directly.
3. Named Constructor
Named constructors provide multiple ways to create instances of a class with different initialization logic.
Example
class Circle {
double radius;
// Default constructor
Circle(this.radius);
// Named constructor
Circle.unitCircle() : radius = 1.0; // Initializes radius to 1.0
}
void main() {
Circle circle1 = Circle(5);
Circle circle2 = Circle.unitCircle();
print('Circle1 Radius: ${circle1.radius}'); // Output: Circle1 Radius: 5
print('Circle2 Radius: ${circle2.radius}'); // Output: Circle2 Radius: 1.0 }
Explanation
- Circle.unitCircle(): This named constructor initializes a
Circle
object with a radius of 1.0.
4. Redirecting Constructors
Redirecting constructors allow you to call another constructor from within a constructor.
Example
class Rectangle {
double width;
double height;
// Parameterized constructor
Rectangle(this.width, this.height);
// Redirecting constructor
Rectangle.square(double size) : this(size, size); // Calls the main constructor }
void main() {
Rectangle square = Rectangle.square(4);
print('Width: ${square.width}, Height: ${square.height}'); // Output: Width: 4, Height: 4
}
Explanation
- Rectangle.square(double size): This constructor redirects to the main constructor, allowing the creation of a square by providing a single side length.
5. Factory Constructor
Factory constructors are special constructors that don’t necessarily create a new instance of the class. They can return an existing instance or a subtype.
Example
class Singleton {
static final Singleton _instance = Singleton._internal();
// Private constructor '
Singleton._internal();
// Factory constructor
factory Singleton() {
return _instance; // Always returns the same instance }
}
void main() {
var instance1 = Singleton();
var instance2 = Singleton();
print(instance1 == instance2); // Output: true
}
Explanation
- Singleton._internal(): The private constructor ensures that instances cannot be created directly.
- factory Singleton(): This factory constructor always returns the same instance, implementing the Singleton pattern.
6. Initializer List
You can use an initializer list to set properties before the constructor body runs, which is useful for final properties.
Example
class Point {
final double x;
final double y;
// Initializer list Point(this.x, this.y) : assert(x >= 0 && y >= 0); // Ensures x and y are non-negative }
void main() {
Point point = Point(3, 4);
print('Point: (${point.x}, ${point.y})'); // Output: Point: (3, 4) }
Explanation
- assert(x >= 0 && y >= 0): This initializer list checks that the values of
x
andy
are non-negative during the object creation.
Constructors in Dart are essential for initializing objects. They provide flexibility through various types, such as default, parameterized, named, redirecting, factory constructors, and initializer lists. Understanding how to effectively use constructors is crucial for building robust Dart applications and managing object creation efficiently. By mastering these concepts, you'll be better equipped to design and implement complex classes in your Dart programs.
PLAY QUIZ