Singletons with factory constructors

Last updated: 14.09.2020 - 22:49 by Boehrsi

Singletons are used to provide a single instance of an object to the whole project. Even though there are multiple ways to achieve this, one of the cleanest is to use a factory constructor in conjunction with a private constructor.

DO use factory constructors to provide singeltons

class DatabaseProvider {
  static DatabaseProvider _instance;

  factory DatabaseProvider() {
    _instance ??= DatabaseProvider._internal();
    return _instance;
  }

  DatabaseProvider._internal();
}