CodeBlanks Logo Icon CodeBlanks

factory

Learn flexible creation with factory constructors.

factory constructor

A factory constructor does not have to produce a new instance every time; it may return an existing instance or a subclass instance. It starts with the factory keyword.

Example: factory User.guest() { return User('Guest'); }. The factory body must contain a return; it cannot assign fields directly like a default constructor. Factories fit caching, singletons and conditional creation. A normal constructor always builds a fresh instance; a factory is flexible.

Singleton and caching

The most common use of a factory constructor is the singleton pattern. A static field inside the class holds the instance; the factory returns the same instance on every call.

Example: class Logger { static final Logger _instance = Logger._(); Logger._(); factory Logger() => _instance; }. Here the private named constructor Logger._() is callable only from inside the class; the _instance static field stores it. A Logger() call returns the same instance every time. This shape fits objects that should be unique, such as a logger, configuration or database connection.

Practice Write the User.guest factory

Define the User class; add a String name field and a User(this.name) default constructor. Write a factory User.guest() { return User('Guest'); } factory constructor. In main, create an instance with var u = User.guest(); and call print(u.name).

Starter code

main.dart
// Define the User class
// Add a String name field and the default constructor
// Add factory User.guest()

void main() {
  // Create a User.guest() instance and print u.name
}

Sample solution

main.dart
// Define the User class
class User {
  String name;
  User(this.name);
  factory User.guest() {
    return User('Guest');
  }
}

void main() {
  var u = User.guest();
  print(u.name);
}

Expected output

Guest

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Add the factory keyword

Question
class User {
  String name;
  User(this.name);
  ____ User.guest() { return User('Guest'); }
}
Answer
class User {
  String name;
  User(this.name);
  factory User.guest() { return User('Guest'); }
}

Explanation: The factory keyword marks a constructor that produces flexibly.

2 What must a factory constructor return?

  • An instance of the class itself Correct answer
  • Only a subclass instance
  • Only null
  • Nothing at all

Explanation: A factory must return an instance of the class itself; new or existing makes no difference.

3 Match the factory parts

Term Meaning
factory Keyword
return Body requirement
static Field holding the instance

All lessons in Intermediate