Factory constructor
In the Dart programming language, we find a special type
of constructor known as the “Factory Constructor,” which
provides additional flexibility in the process of creating
objects. So far, we have learned how to use “Generative
Constructors” which create a new instance of the class
only. However, the Factory Constructor can be used to
create a copy of the class itself, or even to create a copy
of a subclass. In addition, it can also be used to return a
cached instance of the class
Factory Constructor rules in Dart:
1.The Factory Constructor must return a copy of the class
or subclass.
2.The word “this” cannot be used within the Factory
Constructor.
3.The Factory Constructor can be named or unnamed and
can be summoned like any normal Constructor.
4.The Factory Constructor cannot access class members.
Example:
class Area {
final int length;
final int breadth;
final int area;
// Initializer list
const Area(this.length, this.breadth) : area = length *
breadth;
}
void main() {
Area area = const Area(10, 20);
print("المساحة هي: ${area.area}");
// الحظ أن هنا قيمة سالبة
Area area2 = const Area(-10, 20);
print("المساحة هي: ${area2.area}");
}