How to get the subtypes of a generic type using `DartType` from `analyzer` package?

可紊 提交于 2019-12-24 00:52:51

问题


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

for example if the type is List<String>, I would like to get String. Also will be useful to get if the type is generic.

Another more complex example would be Map<String, String> where I want to get a list of the subtypes, in this case: [String, String].


回答1:


This one is a little tricky - because DartType actually itself has some super types - the one that will interest you here is ParameterizedType:

import 'package:analyzer/dart/element/type.dart';

Iterable<DartType> getGenericTypes(DartType type) {
  return type is ParameterizedType ? type.typeArguments : const [];
}

I don't know if it's possible to know if the type is generic - after all, it's just a type. But you can check if the type accepts generic parameters, again, using ClassElement:

import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';

bool canHaveGenerics(DartType type) {
  final element = type.element;
  if (element is ClassElement) {
    return element.typeParameters.isNotEmpty;
  }
  return false;
}

Hope that helps!



来源:https://stackoverflow.com/questions/41754912/how-to-get-the-subtypes-of-a-generic-type-using-darttype-from-analyzer-packa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!