thumbnail

Metadata in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Given below is a list of examples of metadata annotations that you may have already seen:

  • @deprecated
  • @override

Above annotations are globally available to all Dart code.

Metadata in Dart can be used for providing additional information to existing code. Metadata annotations usually begin with @ character followed by either a reference to a compile-time constant (such as deprecated) or call to a constant constructor.

Using the @deprecated annotation

class Arithmetic {
  /// deprecated: use [addTwoNumbers]
  /// adds two numbers and returns their addition
  @deprecated
  int add(int a, int b) {
    return a + b;
  }

  // adds two numbers
  int addTwoNumbers(int a, int b) {
    return a + b;
  }
}

main(List<String> args) {
  var arith = new Arithmetic();
  // displays a warning indicating that add is deprecated and it should not be used
  arith.add(2, 3);
  arith.addTwoNumbers(3, 4);
}

Above program produces following output:

5
7

If a programmer uses any object that is marked as deprecated then Dart analysis server will report an information warning telling the programmer to not use deprecated function calls.

Using the @override annotation

@override is used to mark an instance member as overriding a superclass member with he same name.

This annotation can be used with instance methods, instance fields, instance getters, setters etc. However, it is recommended to not override certain things such as fields for avoiding issues.

class Person {
  void sayHello() {
    print('hello from Person!');
  }
}

class Tony extends Person {
  // this metadata constant is used to inform that [sayHello] is overriden
  @override
  void sayHello() {
    super.sayHello();
    print('hello fram Tony!');
  }
}

void main() {
  var t = new Tony();
  t.sayHello();
}

Above program produces following output:

hello from Person!
hello fram Tony!