0

I want to get TypeAnnotation source to get annotations defined on that type

// file1.dart

@Annoation(name :"hello")
class RType { }

// file2.dart

    @Selectors()
    class Example {
      static Rtype hello() => null;
    }

by using ast visitor i am able to get RType ( TypeAnnoation) , but i want to get actual RType and its annotations ..

class SelectorsGenerator extends GeneratorForAnnotation<Selectors> {

AstNode getAstNodeFromElement(Element element) {
  AnalysisSession session = element.session;
  ParsedLibraryResult parsedLibResult =
      session.getParsedLibraryByElement(element.library);
  ElementDeclarationResult elDeclarationResult =
      parsedLibResult.getElementDeclaration(element);
  return elDeclarationResult.node;
}

  @override
  generateForAnnotatedElement(
      Element element, ConstantReader annotation, BuildStep buildStep) {
    if (!(element is ClassElement)) {
      throw Exception("Selectors should be applied on class only");
    }
    element = element as ClassElement;

    final visitor = ExampleVisitor();
    final astNode = getAstNodeFromElement(element);
    astNode.visitChildren(visitor);

    return """
       // Selector
    """;
  }
}


class ExampleVisitor extends SimpleAstVisitor {
        
     @override
     visitMethodDeclaration(MethodDeclaration node) {
             final t= node.returnType; //TypeAnnonation
              t.type // DartType is null here :( 
              //TODO i want to get annotations defined on this type 
        
           }
        }
invariant
  • 8,758
  • 9
  • 47
  • 61

1 Answers1

1

You shouldn't need to switch to the AST model for this, it should be possible to get the annotation with the Element model.

var methods = classElement.methods;
for (var method in methods) {
  var returnType = method.returnType;
  var metadata = returnType.element.metadata;
  // Do something with the annotation.
}
Nate Bosch
  • 10,145
  • 2
  • 26
  • 22