@deprecated
- Dart course
- Intermediate
- Lesson 79/116
- 5 min
Learn the @deprecated annotation.
Deprecation with @deprecated
@deprecated signals that a method or class should no longer be used. It has two forms: @deprecated (no message) and @Deprecated('why') (with a message).
Example: @Deprecated('use useNew() instead') void oldApi() { ... }. Tools that see this tag show the user a warning.
Marking a deprecated API with @deprecated before removing it is good practice. It gives users time to migrate.
Migration and message
The message inside @Deprecated('message') tells the user what to do. For example @Deprecated('use fetchUser instead') suggests the new method.
When you call a deprecated method the IDE strikes it through and shows the message. The code still runs; it is only a warning.
Waiting one or two releases with @deprecated before full removal lets users migrate.
Practice Deprecated and new method
Define a Calculator class. Give it a @Deprecated('use add instead') void oldAdd(int a, int b) method whose body is print(a + b). Also add void add(int a, int b) => print(a + b). In main call add(2, 3).
Starter code
// Define the Calculator class
// oldAdd is deprecated, add is the new method
void main() {
// call the add method
}Sample solution
class Calculator {
@Deprecated('use add instead')
void oldAdd(int a, int b) {
print(a + b);
}
void add(int a, int b) => print(a + b);
}
void main() {
Calculator().add(2, 3);
}Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does @deprecated mark?
- A deprecated API Correct answer
- A new feature
- An error
- A test
Explanation: @deprecated marks a deprecated API.
2 The @Deprecated message
@____('yerine useNew() kullan')
void oldApi() {}
@Deprecated('yerine useNew() kullan')
void oldApi() {}
Explanation: the message form starts with Deprecated.
3 @deprecated parts
| Term | Meaning |
|---|---|
@deprecated |
Deprecated without message |
@Deprecated('...') |
Deprecated with message |
useNew() |
Suggested new method |
oldApi() |
Deprecated method |