CodeBlanks Logo Icon CodeBlanks

Metadata

Learn metadata with @annotation.

Metadata with annotations

An annotation is a label attached on top of a code element. In Dart it starts with the @ sign, for example @override. Annotations give extra information to the compiler and to tools.

The best known example is @override. When a subclass method redefines a superclass method you write @override. This is common for overriding methods such as toString.

Annotations can tag classes, methods, fields and parameters. You can also write your own annotation; the next lesson covers that.

Where annotations attach

Annotations can attach to many code elements. They are written above a class, method, field or parameter. For example @Deprecated('old') marks a method as deprecated.

Multiple annotations can sit side by side: @override @Deprecated('old'). Dart reads them left to right.

Annotations are signals for tools. @override warns the compiler about a wrong override; @deprecated guides the user to a new method.

Practice Point and @override

Define a Point class with int x and int y fields and a Point(this.x, this.y) constructor. Add a String toString() method marked with @override that returns '($x, $y)'. In main create Point(3, 4) and print it with print.

Starter code

main.dart
// Define the Point class: x, y, constructor and a toString method

void main() {
  // create a Point and print it
}

Sample solution

main.dart
class Point {
  int x;
  int y;
  Point(this.x, this.y);
  @override
  String toString() => '($x, $y)';
}

void main() {
  print(Point(3, 4));
}

Expected output

(3, 4)

Questions and answers

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

1 What does an annotation do?

  • Adds metadata to code Correct answer
  • Deletes a variable
  • Stops a loop
  • Makes a class inherit

Explanation: an annotation adds metadata to code.

2 Writing @override

Question
class Dog extends Animal {
  @____
  String toString() => 'Köpek';
}
Answer
class Dog extends Animal {
  @override
  String toString() => 'Köpek';
}

Explanation: @override is written lowercase.

3 Match the annotation parts

Term Meaning
@override Override
@ Annotation sign
@deprecated Deprecated mark
toString() Overridden method

All lessons in Intermediate