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

Time:04-14

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.

CodePudding user response:

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

  • Related