Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there a way to find declared source of predefined annotations? #615

Closed
wurikiji opened this issue Aug 12, 2022 · 1 comment
Closed

Is there a way to find declared source of predefined annotations? #615

wurikiji opened this issue Aug 12, 2022 · 1 comment

Comments

@wurikiji
Copy link

const predefinedAnnotation = SomeAnnotation('this is predefined');

@predefinedAnnotation  // this is the first case
@SomeAnnotation('this is defined as it's needed') // this is the second case
class SomeClass {
}

In this case, I am currently getting a declaration by using below code.

// `element `is `ClassElement` of SomeClass
for (final annotations in element. metadata) {
  print(annotations.toSource());
}

In the first case (predefined annotation), it only prints predefinedAnnotation, the name of the constant variable.
In the second case, it prints what I want. The full code of @SomeAnnotation('this is defined as it's needed').

Is there a way to get the full code in case of predefinedAnnotation?

@natebosch
Copy link
Member

The first step is to get a DartObject for the annotation. I think annotations.computConstantValue() works in most cases, but if the annotation is not resolvable it may return null. With the DartObject you can use a ConstantReader to read fields from it.
https://pub.dev/documentation/source_gen/latest/source_gen/ConstantReader-class.html

See also LibraryReader which has methods for finding annotated elements and creating a ConstantReader for the annotations.

https://pub.dev/documentation/source_gen/latest/source_gen/LibraryReader-class.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants