Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does @ do in Dart programs?

Tags:

metadata

dart

I've just spent 20 hours in learning about the basics of Dart language, but when I find the @ prefix in an open-source Dart program such as here, which I found that most programs use, I wonder what the @ directive do in those programs...

For your information, the official documentation says the following:

Metadata Use metadata to give additional information about your code. A metadata annotation begins with the character @, followed by either a reference to a compile-time constant (such as deprecated) or a call to a constant constructor. Three annotations are available to all Dart code: @deprecated, @override, and @proxy. For examples of using @override and @proxy, see the section called “Extending a Class”. Here’s an example of using the @deprecated annotation:

However, what "additional information" does the @ directive add to the code? If you create an instance by writing the following constructor

@todo('seth', 'make this do something')

, instead of the following constructor, which is the default:

todo('seth", 'make this do something')

, what is the benefit I can get from the first constructor?

I've got that using the built-in metadata such as @deprecated and @override can give me an advantage of being warned in running the app, but what can I get from the case on the custom @todo, or the aforementioned linked sample code over Github?

like image 383
Blaszard Avatar asked Mar 11 '26 09:03

Blaszard


1 Answers

Annotations can be accessed through the dart:mirrors library. You can use custom annotations whenever you want to provide additional information about a class, method, etc. For instance @MirrorsUsed is used to provide the dart2js compiler with extra information to optimize the size of the generated JavaScript.

Annotations are generally more useful to framework or library authors than application authors. For instance, if you were creating a REST server framework in Dart, you could use annotations to turn methods into web resources. For example it might look something like the following (assuming you have created the @GET annotation):

@GET('/users/')
List<User> getUsers() {
 // ...
}

You could then have your framework scan your code at server startup using mirrors to find all methods with the @GET annotation and bind the method to the URL specified in the annotation.

like image 96
Pixel Elephant Avatar answered Mar 14 '26 08:03

Pixel Elephant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!