Annotations

If you want to add additional data to your code, you can use the metadata structure in Dart. This data is bound to an annotation, which starts with the @ character, a convention familiar from other languages. After the @ symbol, there is either a call to a constant constructor or a constant representing the name of the annotation. If it involves a constant constructor, variables can be passed to the annotation.

Creating an annotation in Dart is simpler than in Java or Kotlin. They are just normal classes without any additional code. Let's create a Todo annotation with the following API:

val todoAnnotation = ClassSpec.builder("Todo")
    .properties(
        PropertySpec.builder("who", String::class)
            .modifier(DartModifier.FINAL)
            .build(),
        PropertySpec.builder("who", String::class)
            .modifier(DartModifier.FINAL)
            .build()
        )
        .constructor(
            ConstructorSpec.builder("Todo")
                .modifier(DartModifier.CONST)
                .parameters(
                    ParameterSpec.builder("who").build(),
                    ParameterSpec.builder("what").build()
                )
                .build()
        )
        .build()

An annotation can also be added to a function, constructor, and other parts of the language features. The following example shows how you can apply an annotation to a function.

val function = FunctionSpec.builder("doSomething")
    .annotation(
        AnnotationSpec.builder(ClassName("Todo"))
                .content("%C", "Glados")
                .content("%C", "Just do something")
                .build()
        )
    .addCode("print(%C);", "The cake is a lie!")
    .build()

Last updated