Metadata

What is Metadata?

The metadata is to a data that provides information about other data.

Use metadata to give additional information to the caller about your code usage.

How to use metadata?

  1. Two annotations are available to all Dart code: @deprecated and @override.
  2. A metadata annotation begins with the character @

Deprecated annotation

You can use the @deprecated annotation to indicate that this method is deprecated use another one instead.

Using the @deprecated annotation:

class Person {
  /// _Deprecated: Use [fullName] instead._
  
  String personName(String firstName, String lastName) {
    return '$firstName, $lastName';
  }

  String fullName(String firstName, String lastName) {
    return '$firstName $lastName';
  }
}

Why we deprecated the personName method:

  1. personName returns the full name of the person, so method name declaration is not as per its functionality
  2. This method returns the full name with , not appropriate.
  3. Here provides the information to the caller that the personName() method is deprecated, instead of that use fullName().

Override annotation

You can use the @override annotation to indicate that you are intentionally overriding a method.

Using the @override annotation:

class Person {
  
  String fullName(String firstName, String lastName) {
    return '$firstName, $lastName';
  }
}

class Manager extends Person {
  /// _Override: Removes the comma `,` while displaying managers full name
  
  String fullName(String firstName, String lastName) {
    return '$firstName $lastName';
  }
}

main() {
  var person = Person();
  print(person.fullName('Rock', 'Star')); // Rock, Star

  var manager = Manager();
  print(manager.fullName('Rock', 'Star')); // Rock Star
}

Custom metadata annotation

In Dart, you can create your own metadata annotations.

Define a @task annotation that takes two arguments:

library task;

class Task {
  final String list;

  final String taskName;

  const Task(this.list, this.taskName);
}

Use @task annotation:

import 'task.dart';

('Project Name', 'Complete UX/UI design for home screen')
void showTask() {
  print('showing task');
}

main() {
  showTask();
}