Home > Blockchain >  Dart: Is it possible to pass a generic type to a class as a variable
Dart: Is it possible to pass a generic type to a class as a variable

Time:06-12

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.

CodePudding user response:

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>();
}

CodePudding user response:

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>());
}
  • Related