Constructors in Dart are special methods used to create and initialize objects. They play a crucial role in Dart Objects and Dart Classes.
If you don't define a constructor, Dart provides a default one. It takes no arguments and creates an instance of the class.
class Person {
String name;
Person(); // Default constructor
}
void main() {
var person = Person();
}
Dart allows you to create multiple constructors with different names. This is useful for providing alternative ways to create objects.
class Point {
double x, y;
Point(this.x, this.y);
Point.origin() {
x = 0;
y = 0;
}
}
void main() {
var p1 = Point(2, 3);
var p2 = Point.origin();
}
These constructors accept parameters to initialize object properties.
class Rectangle {
double width, height;
Rectangle(this.width, this.height);
}
void main() {
var rect = Rectangle(10, 20);
}
Initializer lists allow you to initialize instance variables before the constructor body runs.
class Person {
String name;
int age;
Person(String name, int age)
: name = name.toUpperCase(),
age = age {
print('Creating Person: $name, $age years old');
}
}
For classes whose objects never change, you can define a constant constructor. This optimizes performance and memory usage.
class ImmutablePoint {
final int x;
final int y;
const ImmutablePoint(this.x, this.y);
}
void main() {
const point = ImmutablePoint(1, 2);
}
Factory constructors provide more flexibility in object creation. They can return instances of subclasses or even cached instances.
class Logger {
final String name;
static final Map _cache = {};
factory Logger(String name) {
return _cache.putIfAbsent(name, () => Logger._internal(name));
}
Logger._internal(this.name);
}
Constructors are fundamental in Dart for creating objects. They offer flexibility in object initialization and play a crucial role in implementing Dart Inheritance and managing object lifecycles. Understanding different types of constructors and their use cases is essential for writing efficient and maintainable Dart code.