What is the factory keyword in Dart?
Overview
In Dart, we use the factory keyword to identify a default or named constructor. We use the factory keyword to implement constructors that decides whether to return a new instance or an existing instance.
Syntax
class Class_Name {
factory Class_Name() {
// TODO: return Class_name instance
}
}
We must follow some rules when using the factory constructor.
- The
returnkeyword need to be used. - It does not have access to the
thiskeyword.
Return value
A factory constructor can return a value from a cache or a sub-type instance.
Example
The following code shows how to use the factory keyword in Dart:
// create Class Carclass Car {//class propertiesString name;String color;//constructorCar({ this.name, this.color});// factory constructor that returns a new instancefactory Car.fromJson(Map json) {return Car(name : json['name'],color : json['color']);}}void main(){// create a mapMap myCar = {'name': 'Mercedes-Benz', 'color': 'blue'};// assign to Car instanceCar car = Car.fromJson(myCar);//display resultprint(car.name);print(car.color);}
Explanation
- Line 3: We define a class
Car. - Lines 5-6: We define two parameters,
nameandcolorof string type. - Line 9: We create a parameter constructor.
- Lines 12-15: We create a factory constructor that returns a new instance.
- Line 18: We define the
main()function. - Line 20: We create a
MapnamedmyCar. - Line 22: We assign
myCarto the Class instancecar. - Lines 24-25: Finally, we display the results.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved