Open In App

Dart – Metadata

Last Updated : 12 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Metadata basically is a piece of data that tells us about the underlying piece of data. It is data about data. In the case of Dart programming, metadata can be used to tell us more about the code. Whenever we interact with the new piece of code we can infer information related to it with the help of metadata.

In dart a metadata annotation starts with @ symbol, followed by a call to a constant constructor or a compile-time constant such as override. @override and @deprecated are available to all dart codes.

We will be seeing an example of @override annotation to understand it clearly –

Dart




class geek1 {
  void code() {
    print("I am at level 1");
  }
}
  
class geek2 extends geek1 {
  @override
  void code() {
    print("I am at level 2");
  }
}
  
void main() {
  geek2 m = new geek2();
  m.code();
}


Output:

I am at level 2

Explanation:

From the above code, we can infer that the child class is overriding the parent class method. The @override annotation makes this information much more clear. Apart from the annotations available in dart we can create our own metadata annotation. 

Example:

Dart




class Implement {
  final String what;
  final String by;
  
  const Implement(this.what, this.by);
}
  
@Implement('the following function', 'Geek1')
void geekFunc() {
  print('Implement me');
}
  
void main() {
  geekFunc();
}


Output:

Implement me

Here we have defined the @Implement annotation using a constant constructor. It has two arguments namely what for what is to be implemented and the other is by which indicate by whom it is to be implemented. 

Metadata can be used before a library, type parameter, function, constructor, class, etc, and before an import or export directive. We can get the metadata at runtime with the help of reflection.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads