Posted on :: Tags: , , , ,

Dart supports factory constructors, which can return an instance of a subtype or even a cached instance. To create a factory constructor, use the factory keyword:

class Square extends Shape {}

class Circle extends Shape {}

class Shape {
  Shape();

  factory Shape.fromTypeName(String typeName) {
    if (typeName == 'square') return Square();
    if (typeName == 'circle') return Circle();

    throw ArgumentError('I don\'t recognize $typeName');
  }
}