首页 > 解决方案 > Dart 中的静态构造函数

问题描述

如何在 Dart 中编写静态构造函数?

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

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

}

标签: dartconstructorstatic

解决方案


Dart 中没有静态构造函数。命名构造函数,例如Shape.circle()通过类似的东西来实现

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

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

您可能还对这个工厂构造函数问题感兴趣

更新:几个静态初始化器变通办法

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

或者,如果类的用户不打算访问静态内容,则可以将其移出类。

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

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

推荐阅读