Jochen
Jochen

Reputation: 616

Dart: Is it possible to pass a generic type to a class as a variable?

I have a class with a generic type and I want to pass that type as a variable. Is there a way to achieve this?

abstract class MainType {}

class TypeA extends MainType {}

class TypeB extends MainType {}

class MyClass<T extends MainType> {}

Type getType(String key) {
  if (key == 'a') return TypeA;

  return TypeB;

}

MyClass constructMyObject(String key) {
  final type = getType(key);
  return MyClass<type>(); //<<-- This here doesn't work
}

The background is, that I want to parse the type from a string and pass that type to various classes.

Upvotes: 1

Views: 2107

Answers (2)

Jochen
Jochen

Reputation: 616

So, as far as I understood this isn't possible without some workarounds.

One potential solution I found is the type_plus package. But I haven't tried it.

I ended up doing something like this:

abstract class MainType {}

class TypeA extends MainType {}

class TypeB extends MainType {}

class MyClass<T extends MainType> {}

R decodeType<R>(String? key, R Function<T extends MainType>() builder) {
  if (key == 'a') return builder<TypeA>();

  return builder<TypeB>();
}

MyClass constructMyObject(String key) {
  // ignore: unnecessary_lambdas
  return decodeType(key, <T extends MainType>() => MyClass<T>());
}

Upvotes: 1

Ivo
Ivo

Reputation: 23154

MyClass is not of type T so you can't return a MyClass object from it.

Is this what you want?

MyClass constructMyObject<T extends MainType>() {
  return MyClass<T>();
}

Upvotes: 0

Related Questions