Final vs Const in Dart. With examples
All of us have used final and const in our dart code while building flutter applications. Essentially final and const are used for same things i.e declaring a variable that does not change its value later.
Even though these two keywords seem to be same on the surface but have their subtle differences. I will be showing these through this article.
1. Final makes the variable constant at run time, const makes the variable constant at compile time
The value of a final variable can be computed at run time (eg: DateTime.now()) and then it will become constant but for const the value should be constant since the compile time
2. Const variable makes the object’s entire deep state strictly fixed at compile-time and the object becomes completely immutable.
The second difference is that the object which we declare as const becomes completely immutable whereas this does not happen with final. Let me explain this with example of List.
Declare a list as final then:
We are able to change the ith element of the list due to its mutability
Declare a list as const then:
We cannot change the ith index of the list as it makes the list immutable
Conclusion
I hope that with this article the differences between final and const are now clear to you and when asked about final vs const in dart you would be able to answer it clearly.