What Is Metadata?
Metadata is essentially a piece of information that can provide additional context to your code. This information can be used by tools such as Dart Editor, and eventually by your own code via mirror-based reflection.
According to the Dart Specification "Metadata can appear before a library, class, typedef, type parameter, constructor, factory, function, field, parameter, or variable declaration and before an import or export directive."
Using The Dart 'meta' Library
Since this is a package library, you'll need to add a reference to it in your application pubspec, and then run pub install (see pub.dartlang.org for more information about this process). Once available, you can import the library like so:
Now that the metadata types are in scope for your app, it's time to put them to good use!
Let's say you have a class for a function that you no longer want users of your library to use. By marking your object with the @deprecated tag, the Dart editor will strike-through any references to it, giving a great visual clue to the developer that they should use a new approach.
Using the @deprecated Metadata Type
First lets look at our function before @deprecated is applied:
Now this one I really like, because it's actually helped me catch a few inheritance-related bugs in my code. Let's look at this example where we have a class Bar which inherits from a class Foo, and Bar wants to override some methods in Foo:
Using the @override Metadata Type
By using the @override metadata type, we can see that the editor is helping us identify a problem in our Bar class, where we have a typo in the override class name. Notice how we get no help on the 'donothing()' method in Bar, when we probably wanted to override 'doNothing()' in Foo.
In larger, non-trivial applications these kinds of bugs can be nasty to track down, if you consider that this code...
...will happily execute and give you a result of "doThat" from Foo instead of the expected "Do that other thing." from Bar - leaving you with clenched fists and pulled hair as you try to trace down the problem.. In short, using @override every time you expect to be overriding a superclass method will help you avoid a whole class of bugs in your code.
SummaryDart's metadata functionality is still in early days, but already proves quite helpful when combined with tools such as the Dart Editor. Liberal use of @deprecated and @override will go along way toward making your code easier to work with and troubleshoot. Give it a try in your code today and give your feedback to the Dart team.