CodeBlanks Logo Icon CodeBlanks

Summary - Metadata

Combine annotations, @override and reflection to write an annotation processor.

Summary: Metadata

In this group you saw annotations, the @override and @deprecated tags, writing custom annotations and reflection with dart:mirrors. Annotations add metadata to code; @override catches wrong overrides.

Now we combine them: we will define a custom annotation and apply it to a method. This shows how annotations carry labels.

Remember: an annotation is a class with a const constructor; @override is recommended; @deprecated warns.

Practice The Review annotation

Define a Review annotation class with a final String note field and a const Review(this.note) constructor. Write a Report class with a @Review('important') void generate() { print('generated'); } method. In main call Report().generate().

Starter code

main.dart
// Define the Review annotation class (note, const constructor)
// Define the Report class and the generate method

void main() {
  // call the generate method
}

Sample solution

main.dart
class Review {
  final String note;
  const Review(this.note);
}

class Report {
  @Review('important')
  void generate() {
    print('generated');
  }
}

void main() {
  Report().generate();
}

Expected output

generated

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Concept matching

Term Meaning
@override Override
@deprecated Deprecated mark
class Todo Custom annotation
dart:mirrors Reflection

2 What is a custom annotation made of?

  • An enum
  • A Future
  • A class with a const constructor Correct answer
  • An abstract method

Explanation: a custom annotation is a class with a const constructor.

3 Applying an annotation

Question
@____('önemli')
void generate() {}
Answer
@Review('önemli')
void generate() {}

Explanation: the annotation is applied with @Review.

All lessons in Intermediate