- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Immutable annotation in Dart Programming
We know that const keyword provides immutability in objects. But what about the cases, where we want the entire class to be immutable in nature.
In such cases, we make use of the immutable annotation that is present inside the meta package of dart library.
Syntax
import 'pacakge:meta/meta.dart'; @immutable class User { String name; }
It should be noted that once we declare any class with the immutable notation, all its object and the object properties and methods will be immutable as well.
Example
Consider the example shown below −
import 'pacakge:meta/meta.dart'; @immutable class User { final String name; User(this.name); User.withPrint(this.name){ print('New user added ${this.name}'); } } void main(){ var u = User.withPrint('Mukul'); u = {}; print(u.name); }
In the above code, we declared the entire class as immutable and hence any object that we instantiate through it will be immutable as well. Inside the main function, we are trying to assign a different value to the variable u, which will give us a compile error.
Output
Error: Overriding not allowed, as 'u' is immutable. u = {}; ^^^^
Advertisements