What are metadata annotations
Start with @, attach static metadata information to code. They are read by compilers, IDEs and static analyzers and do not affect runtime logic.
Two valid formats:
- Built-in compile-time constants:
@override,@deprecated - Constant constructor invocations:
@Deprecated("Message"), custom annotations like@Todo("xxx", "xxx")
Commonly applied to classes, methods, variables, functions, parameters, imports, enums, etc.
@Deprecated
Marks an obsolete API. You must specify the replacement and removal timeline. It also has static methods for fine-grained restriction scenarios.
class Television {
/// Replacement: use turnOn
@Deprecated('Use turnOn() instead. This method will be removed by the end of 2026')
void activate() {
turnOn();
}
void turnOn() {
print("TV powered on");
}
}
// Examples of granular deprecation restrictions
@Deprecated.instantiate() // Disallow instantiating this class with new
class OldDevice {}
@Deprecated.extend() // Disallow other classes from extending this class
class Base {}
// Attempting to extend Base triggers deprecation warnings in the editor
class Sub extends Base {}
void main() {
Television tv = Television();
// Calling @Deprecated method shows strikethrough + IDE warnings
tv.activate();
// Recommended new method
tv.turnOn();
// Instantiating OldDevice triggers @Deprecated.instantiate() warning
OldDevice device = OldDevice();
}
Code language: Dart (dart)
The code above still compiles and runs normally. Warnings will only appear in IDEs and compilers. You can test this with Android Studio or IntelliJ IDEA.
@deprecated
No custom message, simple deprecation marker. Prefer using @Deprecated("Description")
@deprecated
void oldFunc() {}
Code language: Dart (dart)
@override
Marks members that override identical superclass / interface members. The IDE performs validation: misspelled method names will show red errors.
class Animal {
void speak() {}
}
class Dog extends Animal {
// @override marks overriding parent speak method
@override
void speak() {
print("Woof");
}
}
class Cat extends Animal {
@override
void speak() {
print("Meow");
}
}
class Pig extends Animal {
// No override
}
void main() {
Animal dog = Dog();
Animal cat = Cat();
Animal pig = Pig();
dog.speak(); // Output: Woof
cat.speak(); // Output: Meow
pig.speak();
}
Code language: Dart (dart)
@pragma
Pass low-level optimization / identification directives to compilers and static analyzers, mostly used for low-level development.
// Example: Tell compiler to inline this function
@pragma('vm:prefer-inline')
int add(int a, int b) => a + b;
Code language: Dart (dart)