How can I get the subtypes of an element using the class DartType from the analyzer package?
Asked
Active
Viewed 765 times
1 Answers
5
For those wondering, the DartType
class is a statically resolved type that is created by the analyzer
package, Dart's static tooling package. The author is asking how they can get other types given a DartType
- I think you mean super types, i.e. types that you inherit or implement.
(If you simply wanted to check if the DartType
is a subtype of something, you could use isSubtypeOf
)
We can get a hold of the Element
that the DartType
originates from, and then, if it is a ClassElement
, simply return all of the super types, otherwise perhaps default to an empty list:
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
/// Returns all sub-types of [type].
Iterable<DartType> getSubTypes(DartType type) {
final element = type.element;
if (element is ClassElement) {
return element.allSupertypes;
}
return const [];
}
This is in analyzer
version 0.29.3
.

matanlurey
- 8,096
- 3
- 38
- 46
-
2sorry, I want the subtypes of a generic type, ie: `List
` I want `String`. – Luis Vargas Jan 20 '17 at 01:55 -
should I change the question? – Luis Vargas Jan 20 '17 at 01:55
-
1That or ask another one - I imagine this will be useful for someone :) – matanlurey Jan 20 '17 at 01:56
-
other question: http://stackoverflow.com/questions/41754912/how-to-get-the-subtypes-of-a-generic-type-using-darttype-from-analyzer-packa – Luis Vargas Jan 20 '17 at 02:03
-
1@matanlurey do you know how to get DartType from a Type ? Because on my generator I want to use isSubtypeOf but can't as I only have the Type not the dartType to compare to – jaumard Mar 01 '19 at 09:32