Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get generic Type?

Tags:

flutter

dart

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.

like image 547
Rémi Rousselet Avatar asked Oct 19 '18 11:10

Rémi Rousselet


1 Answers

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);
}
like image 50
Xavier Avatar answered Oct 11 '22 14:10

Xavier