Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static constructor in Dart

How to write static constructor in Dart?

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

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

}
like image 867
Arif Avatar asked Jan 19 '20 12:01

Arif


People also ask

What is static method in Dart?

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.

What is a static constructor?

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.

What are constructors in Dart?

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.

What is default constructor in Dart?

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.


1 Answers

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();
  }
}
like image 79
Jacob Phillips Avatar answered Oct 08 '22 16:10

Jacob Phillips