How to write static constructor in Dart?
class Generator
{
static List<Type> typesList = [];
//static
//{ /*static initializations*/}
}
static methods are members of the class rather than the class instance in Dart. static methods can only use static variables and call the class's static method. To access the static method, we don't need to create a class instance. To make a method static in a class, we use the static keyword.
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed only once. It is called automatically before the first instance is created or any static members are referenced.
Dart Constructors A constructor is a special function of the class that is responsible for initializing the variables of the class. Dart defines a constructor with the same name as that of the class. A constructor is a function and hence can be parameterized.
A Constructor which has no parameter is called default constructor or no-arg constructor. It is automatically created (with no argument) by Dart compiler if we don't declare in the class. The Dart compiler ignores the default constructor if we create a constructor with argument or no argument.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With