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 −

 Live Demo

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 = {};
   ^^^^

Updated on: 21-May-2021

442 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements