Israr
Israr

Reputation: 314

How to count the number of instances of a Class in Dart?

In Java, we can use the instance initialization block to keep track of count of any class objects.

So, in dart how can we do that for a class with const Constructor?

I know that for a non-constant Constructor, we can achieve that by creating a static variable then incrementing its value in Constructor body.

But as we know that, const Constructor can't have a body, then how to keep track of number of instances created for a particular class ?

Upvotes: 0

Views: 419

Answers (2)

lrn
lrn

Reputation: 71813

Not only can a (generative, non-redirecting) const constructor not have a body, it also cannot run any code with a side-effect. That's by design, so there is no way around it.

There really is no way, inside the language and program, to count instances of that class.

Using the developer tools is the only viable approach, because it can scan the actual runtime memory and see how many instances exist.

Upvotes: 1

hacker1024
hacker1024

Reputation: 3668

There can only be one instance of a class made with a const constructor. The one instance is instantiated during compilation, and all const calls to the constructor return it.

If you want to count the number of times a const constructor is used in a non-const context, this is not possible, because code with the potential to be executed during compilation cannot cause runtime side-effects.

Consider using a factory constructor for this purpose, like so:

class MyClass {
  static var _instances = 0;

  const MyClass();

  factory MyClass.tracked() {
    ++_instances;
    return const MyClass();
  }
}

Upvotes: 1

Related Questions