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.

  1. The return keyword need to be used.
  2. It does not have access to the this keyword.

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 Car
class Car {
//class properties
String name;
String color;
//constructor
Car({ this.name, this.color});
// factory constructor that returns a new instance
factory Car.fromJson(Map json) {
return Car(name : json['name'],
color : json['color']);
}
}
void main(){
// create a map
Map myCar = {'name': 'Mercedes-Benz', 'color': 'blue'};
// assign to Car instance
Car car = Car.fromJson(myCar);
//display result
print(car.name);
print(car.color);
}

Explanation

  • Line 3: We define a class Car.
  • Lines 5-6: We define two parameters, name and color of 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 Map named myCar.
  • Line 22: We assign myCar to the Class instance car.
  • Lines 24-25: Finally, we display the results.

Copyright ©2024 Educative, Inc. All rights reserved