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.
class Class_Name {
factory Class_Name() {
// TODO: return Class_name instance
}
}
We must follow some rules when using the factory
constructor.
return
keyword need to be used.this
keyword.A factory
constructor can return a value from a cache or a sub-type instance.
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);}
Car
.name
and color
of string type.main()
function.Map
named myCar
.myCar
to the Class instance car
.