static constructor in Dart

Inspired by @Mahmoud salah eldien saber answer Create a singleton, and static variable reference to the singleton variable

void main() {
  
  print('${Singleton.add()}');
  print('${Singleton.add()}');
  print('${Singleton.add()}');
  print('${Singleton.add()}');     
}

class Singleton {
  Singleton();
    
  //static
  static List<int> typeList = Singleton.internal()._typeList;
  static List<int> add() {
    typeList.add(1);
    return typeList;
  }  
  List<int> _typeList = [];
  factory Singleton.internal() {  
    var s = Singleton();
    for(int i = 0 ; i < 5; i++ ) {
      s._typeList.add(2);
    }   
    return s;
  }    
   
}

I also want to find a official answer for this question.


There is no such thing as a static constructor in Dart. Named constructors such as Shape.circle() are achieved by something like

class A {
  A() {
    print('default constructor');
  }
  A.named() {
    print('named constructor');
  }
}

void main() {
  A();
  A.named();
}

You might also be interested in this factory constructors question

Update: A couple of static initializer work-arounds

class A {
  static const List<Type> typesList = [];
  A() {
    if (typesList.isEmpty) {
      // initialization...
    }
  }
}

Or the static stuff can be moved out of the class if it isn't meant to be accessed by users of the class.

const List<Type> _typesList = [];
void _initTypes() {}

class A {
  A() {
    if (_typesList.isEmpty) _initTypes();
  }
}

Static variable declarations are initialized lazily to avoid costly initialization (and attendant slowness) at program startup.. The first time a static variable v is read, it is set to the result of evaluating its initializer.

https://groups.google.com/a/dartlang.org/forum/#!topic/misc/dKurFjODRXQ


You can initialize static members by calling the class.member directly, inside the constructor:

class A {
  static int a;
  static int b;

  A(int a, int b) {
    A.a ??= a; ///by using the null-equals operator, you ensure this can only be set once
    A.b ??= b;
  }
}


main(){
  A(5,10);
  A(2,4);
  assert(A.a == 5);
  assert(A.b == 10);
}