How to get subtypes using `DartType` class from the `analyzer`?

Issue

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

Solution

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.

Answered By – matanlurey

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.