Dart Constructors
Learn Dart through interactive, bite-sized lessons. Build Flutter apps and master modern development.
Start Dart Journey →Constructors in Dart are special methods used to create and initialize objects. They play a crucial role in Dart Objects and Dart Classes.
Types of Constructors
1. Default Constructor
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();
}
2. Named Constructor
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();
}
3. Parameterized Constructor
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);
}
Constructor Initializer Lists
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');
}
}
Constant Constructors
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
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);
}
Best Practices
- Use named constructors for clarity when a class can be constructed in multiple ways.
- Leverage initializer lists for efficient object initialization.
- Consider using factory constructors for complex object creation logic.
- Utilize const constructors for immutable objects to improve performance.
Conclusion
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.