Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the immutable annotation work in Dart?

Tags:

dart

How does the @immutable annotation work?

I learned annotations are related to meta and reflection recently.

However, I cannot find the source code it proves.

Please tell me how to work or the source code.

like image 386
zbk Avatar asked Jan 26 '26 03:01

zbk


1 Answers

Annotations by themselves don't do anything. If you look at the source code for an annotation such as Immutable, it's not very interesting. Annotations are just special tags that live in the source code; they don't affect the compiled code.

An annotation usually must work in tandem with some tool that does static analysis of your code and that looks for that annotation. In the case of @immutable, that's handled by Dart's static analyzer when you run dart analyze. (Other packages might provide their own annotations that are handled by other tools; for example, package:mockito has @GenerateNiceMocks/@GenerateMocks annotations that are processed when you run its build-runner step.)

It looks like the analyzer handles @immutable in its internal _checkForImmutable function.

like image 116
jamesdlin Avatar answered Jan 29 '26 05:01

jamesdlin