Search code examples
dartconstructorstatic

static constructor in Dart


How to write static constructor in Dart?

class Generator
{
   static List<Type> typesList = [];

   //static
   //{ /*static initializations*/}

}

Solution

  • 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();
      }
    }