Junior — Middle
Can you name the main types of constructors used in Dart?
sobes.tech AI
Answer from AI
In Dart, the main types of constructors include:
- Default constructor: Initializes an object using parameters.
class Point {
int x, y;
Point(this.x, this.y);
}
- Named constructors: Allow creating additional constructors with names.
class Point {
int x, y;
Point(this.x, this.y);
Point.origin() {
x = 0;
y = 0;
}
}
- Initializer list constructors: Used for initializing final fields or calling superclass constructors.
class Point {
final int x, y;
Point(this.x, this.y);
Point.origin() : x = 0, y = 0;
}
- Factory constructors (
factory): Allow returning an existing object or subclass.
class Logger {
factory Logger() {
return _cache ??= Logger._internal();
}
Logger._internal();
static Logger _cache;
}
- Constant constructors (
const): Create immutable objects that can be created at compile time.
class ImmutablePoint {
final int x, y;
const ImmutablePoint(this.x, this.y);
}
These types cover the main ways of creating and initializing objects in Dart.