Dart Metadata

 

Dart Metadata

The Dart Metadata is used to specify the Dart program with additional information. It usually starts with @ symbol, followed by either a reference of the compile-time constant or a call to a constant constructor.

Creating Metadata Annotation

In Dart, we can define our own metadata annotations.

Let's understand the following example -

Example -

Here's an example of defining a @student annotation that takes two arguments -

library student;  

  1. Class Student {  
  2.      final String studentName;  
  3.      final String rollno;  
  4.      const Student(this.studentName, this.code);  
  5. }  

And, here is the following example we are using @student annotation.

  1. import 'student.dart' ;  
  2. @Student('studentName''rollno')  
  3. void greetHii() {  
  4.      print("Hii Welcome to Javatpoint");  
  5. }  

In Dart, metadata generally define just before a library name, class, typedef, field, type parameter, factory, function, constructor, parameter, or variable declaration and before an import or export directive. We can retrieve the metadata using reflection in runtime.

Let's understand the following example.

Example -

  1. class Human{  
  2.    @Overridden method  
  3.     void run()  
  4.    {  
  5.       print("Human is running");  
  6.    }  
  7. }  
  8. class Man extends Human{  
  9.    @Overriding method  
  10.     void run(){  
  11.       print("Boy is running");  
  12.    }  
  13. }  
  14. void main(){  
  15.       Man m = new Man();  
  16.       //This will call the child class version of run()  
  17.       m.run();  
  18. }  

Output:

Boy is running

In the above code, we have provided the addition information to the both parent class and child class functions

Comments