4

How can I get the subtypes of an element using the class DartType from the analyzer package?

Luis Vargas
  • 2,466
  • 2
  • 15
  • 32

1 Answers1

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