Immutability in Dart Programming

Immutability is the ability to remain constant. Whenever we talk about immutability we mention the immutable nature.

In object oriented and functional programming, we make use of the immutable nature of objects a lot. Being immutable means that the state of the object cannot be modified after its creation.

It is a very important topic these days when we talk about front-end development, as there are several occasions and scenarios where we want to maintain the state and the way to do that is to make use of immutability.

In Dart, there are different ways with which we can achieve immutability and sometimes we can enforce immutability on our objects and classes as well.

Making use of the 'const' keyword handles the immutability of the variable or object very well.

It should be noted that the const keyword in dart is very different from that present inside the javascript, even though they use the same syntax.

Let's consider an example, where we are declaring a const in javascript, and then try to reassign it to something else, first reassign the entire object, then reassign some property of it.


Consider the example shown below −

// Define USER as a constant and give it an initial value.
const USER = { name: 'Mukul'; }

// This will throw an error.
USER = {};

// But this will not. = 'Rahul';


In the above js code, we can see that when we tried reassigning the USER withsomething else, it returned an error. But, if we assign the name property of the USER object, no error is encountered.



It happens because in js, the const keyword is just an immutable binding and not an immutable object.

In Dart, the scenario is entirely different, the const keyword ensures that the object remains immutable in nature.


Consider the example shown below −

void main(){
   const user = const {'name': 'Mukul'};

   // Static error: "Constant variables cannot be assigned a value".
   user = {};

   // Runtime error: "Unsupported operation: Cannot modify unmodifiable Map".
   user['name'] = 'Rahul';


Error: Can't assign to the const variable 'user'.
   user = {};
Error: Compilation failed.

Updated on: 21-May-2021


Kickstart Your Career

Get certified by completing the course

Get Started