Custom annotations
- Dart course
- Intermediate
- Lesson 77/116
- 5 min
Learn to write your own annotation class.
Writing a custom annotation
You can write your own annotation. An annotation is simply a class with a const constructor. For example class Todo { final String msg; const Todo(this.msg); } is an annotation class.
You use it as @Todo('fix'). After the @ sign comes the class name and any arguments. Dart binds this label to the element.
Custom annotations are usually combined with code generation tools. On their own they have no runtime effect; they carry label information.
Applying an annotation
You can apply your Todo annotation to a method. Example: @Todo('add tests') void run() { ... }. The annotation is written right before the method.
You can pass arguments to the annotation: @Todo('message'). This corresponds to const Todo('message').
Multiple annotations can attach to one element. Tools can scan these labels and produce reports, for example list all Todo tags.
Practice The Todo annotation
Define a Todo annotation class with a final String msg field and a const Todo(this.msg) constructor. Write a void run() { print('running'); } method marked with @Todo('test'). In main call run().
Starter code
// Define the Todo annotation class (msg, const constructor)
// Define the run method
void main() {
// call the run method
}Sample solution
class Todo {
final String msg;
const Todo(this.msg);
}
@Todo('test')
void run() {
print('running');
}
void main() {
run();
}Expected output
running
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a custom annotation require?
- A method returning a Future
- A class with a const constructor Correct answer
- At least one abstract method
- An enum
Explanation: an annotation is a class with a const constructor.
2 const constructor
class Todo {
final String msg;
____ Todo(this.msg);
}
class Todo {
final String msg;
const Todo(this.msg);
}
Explanation: a const constructor starts with const.
3 Custom annotation parts
| Term | Meaning |
|---|---|
class Todo |
Annotation class |
const Todo(this.msg) |
const constructor |
@Todo('test') |
Application |
final String msg |
Field |