How do i restrict usage of my custom annotation? (dart)

Viewed 58

When i have a custom annotation like this:

class FieldAnnotation{
  const FieldAnnotation();
}

How do i restrict the usage of that annotation to only be applied on fields. Specifically, how do i generate a warning or an error on static analysis?

@FieldAnnotation() // should show a warning or an error
class Test{
  @FieldAnnotation() // should have no problems 
  final String id;  

  Test({required this.id});
}
1 Answers

I hoped, someone had already answered your question. I'm also searching for more detailed information about custom dart annotations.

But perhaps i have found the answer inside the meta package - in meta-meta.dart - to be precise.

As I understand, you can annotate your custom annotation class (annotation definition, not the annotated elements) with @Target(targets) where targets is a Set<TargetKind> where TargetKind is an enum.

Also interesting to see, that it is possible to write an extension on an enum what they did with TargetKind.

Related