getInnerTypeByPosition function

String getInnerTypeByPosition(
  1. TypeAnnotation returnType, {
  2. int at = 0,
  3. bool? useLexeme = true,
})

Implementation

String getInnerTypeByPosition(
  TypeAnnotation returnType, {
  int at = 0,
  bool? useLexeme = true,
}) {
  if (returnType is! NamedType) {
    throw Exception(
      'Return type is not a NamedType, cannot extract class name.',
    );
  }

  NamedType typeToInspect = returnType;

  // Unwrap Future/FutureOr
  if (typeToInspect.name.toString() == 'Future' ||
      typeToInspect.name.toString() == 'FutureOr' ||
      typeToInspect.name.toString() == 'Stream') {
    if (typeToInspect.typeArguments != null &&
        typeToInspect.typeArguments!.arguments.isNotEmpty) {
      TypeAnnotation innerType;
      if (at > 0) {
        innerType = typeToInspect.typeArguments!.arguments[at];
      } else {
        innerType = typeToInspect.typeArguments!.arguments.first;
      }
      if (innerType is NamedType) {
        // print("innerType is NamedType");
        typeToInspect = innerType;
      } else {
        return innerType.toSource();
      }
    }
  }

  final result = switch (useLexeme) {
    true => typeToInspect.name.lexeme,
    _ => typeToInspect.toSource(),
  };
  print("[getInnerTypeByPosition] $result");
  return result;
}