I would like to obtain the Type
of a generic class. Ideally I'd like the following:
Type type = MyClass<int>;
But this is throws a syntax error. What is the proper way to get access this type information?
I know that I can get this type using runtimeType
like so:
final foo = MyClass<int>();
Type type = foo.runtimeType;
But this requires an instance of the object; which doesn't fit my use-case.
Edit: as of Dart 2.15 this trick is not needed anymore
See Dart 2.15 announcement: https://medium.com/dartlang/dart-2-15-7e7a598e508a
var z = List<int>; // New in 2.15.
var z = typeOf<List<int>>(); // Pre-2.15 workaround.
Old answer:
Dart doesn't support type arguments in class literals (https://github.com/dart-lang/sdk/issues/11923)
But you can write a small generic helper:
Type typeOf<T>() => T;
main() {
Type type = typeOf<MyClass<int>>();
print(type);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With