How to write a type signature for a function that accept class itself, not its object

98 Views Asked by At

I'm a newbie in Dart.

I would like to pass a class, NOT a class object, to a function, and it looks like this now:

void passClass(?? Klass) {
  SomeClass obj = Klass();
  ...
}

I don't what to put to ??.

Thanks.

1

There are 1 best solutions below

0
nvoigt On BEST ANSWER

The concept you are looking for is called generics.

void passClass<T>() {
  ...
}

could then be called like this:

passClass<Klass>();

The problem is that you cannot actually make your code work this way, because your code assumes the class that gets passed always has a parameterless constructor. That might be the case for some classes, but not for others.

If you want to create an object of the class you passed, it gets complicated. You can find good solutions at Creating an instance of a generic type in DART