Dart Metadata

metadata in Dart is used to provide more details about the line of code or blocks.

In these tutorials, Discuss how to create metadata and bind this to code.

Metadata contains @ annotation character followed by a string.

The string is a reference to a compile-time constant or calls to a constant constructor.

how to create metadata annotation

We can define user-defined metadata annotation.

Following is an example of creating @Role annotation, that takes two arguments - rolecode, and rolename.

library security;

class Role {
  final String rolecode;
  final String rolename;

  const Employee(this.rolecode, this.rolename);
}

Once the annotation is created, you can use annotations like dart annotations such as @deprecated.

In this example,@Role is used before a function declaration.

import 'security.dart';

@Role('ADMIN', 'ADMINISTRATOR')
void isAdminGranted() {
  print('administrator granted');
}

metadata annotations are used before the following components

  • class
  • library
  • typedef
  • constructor
  • factory
  • function
  • field
  • variable declaration
  • import or export directive