KEMBAR78
Dart Factory Constructor Guide | PDF
0% found this document useful (0 votes)
13 views2 pages

Dart Factory Constructor Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views2 pages

Dart Factory Constructor Guide

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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}");
}

You might also like