Skip to content

alenkart/dart-examples

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 

Repository files navigation

dart-examples

@Annotantions

To make a custom annotation in dart is necessary to create a constant object, the following example are valid annotation declarations:

Creating an annotation

const annotationA = "annotation";
const annotationB = 1;

@annotationA
@annotationB
method() {}

A class with a constant constructor can be use as annotation

class MyAnnotantion {
  final String data;
  //constan constructor
  const MyAnnotantion(this.data);
}

Using the example annotation

Applying the custom annotation to an example class

@MyAnnotantion('Class')
class Example {
  @MyAnnotantion('Property')
  String variable;
  
  @MyAnnotantion('Instance method')
  instanceMethod(@MyAnnotantion('Instance method parameter') variable) {}
  
  @MyAnnotantion('Static method')
  static staticMethod(@MyAnnotantion('Static method parameter') variable) {}
}

Class metadata

@MyAnnotantion('Class')
class Example
final object = Example();
final instanceMirror = reflect(object);
final classMirror = instanceMirror.type;

classMirror.metadata.forEach((metadata) {
    print(metadata.reflectee.data);
});

Result: Class

Class property metadata

@MyAnnotantion('Property')
String variable;
final object = Example();
final instanceMirror = reflect(object);
final classMirror = instanceMirror.type;

classMirror.declarations.forEach((symbol, declaretion) {
    if (declaretion is VariableMirror) {
        declaretion.metadata.forEach((metadata) {
          print(metadata.reflectee.data);
        });
    }
});

Result: Property

Class method metadata

@MyAnnotantion('Instance method')
instanceMethod(@MyAnnotantion('Instance method parameter') variable) {}

@MyAnnotantion('Static method')
static staticMethod(@MyAnnotantion('Static method parameter') variable) {}
final object = Example();
final instanceMirror = reflect(object);
final classMirror = instanceMirror.type;

classMirror.declarations.forEach((symbol, declaretion) {
  if (declaretion is MethodMirror) {
    declaretion.metadata.forEach((metadata) {
      print(metadata.reflectee.data);
    });
  }
});

Result: Instance method, Static method

Class method parameter metadata

//instanceMethod
@MyAnnotantion('Instance method parameter') variable

//staticMethod
@MyAnnotantion('Static method parameter') variable
final object = Example();
final instanceMirror = reflect(object);
final classMirror = instanceMirror.type;

classMirror.instanceMembers.forEach((symbol, method) {
  method.parameters.forEach((parameter) {
    parameter.metadata.forEach((metadata) {
      print(metadata.reflectee.data);
    });
  });
});

Result: Instance method parameter, Static method parameter

About

Dart examples and tutorials

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages