const v/s final… Let’s check what they do! — Flutter 💙

We have two keywords const and final which usually make developers confused! Let’s see in deep how it works.

There are many ways we can create variables in Flutter. Two of them are const and final! If we check their functionality, they both have similar work, to create variables whose values won’t be changed. Then what is the difference? Let’s check it out!

So, when we assign any value to a const variable and again assign it with a different value, it throws an error stating:

Constant variables can't be assigned a value.

Now, let’s try the same with final variable.

Hmm… 🤔 this also throws an error which says:

The final variable 'data' can only be set once.

So, both of them threw almost the same errors that final and const variables can only be assigned once! This is a bit confusing right. Then what is the exact difference? Let’s check out by diving a bit deeper into how both of them are working!

The main difference between const and final is that const can be considered as a compile-time constant while final can be considered as a run-time constant. So when you want the constant value and you are aware of the value to be assigned, at the compile-time itself, you can use const! But let’s say you want a constant value but you don’t know its value at compile-time, then you can use final!

Example for using const:

Here, in the above code snippet, we already knew that the value of data should be Flutter and it should not change in the entire program hence we have used const.

Example for using final:

Here, in the above code snippet, we didn’t know the date but we wanted it to remain constant throughout the program. Hence we have used final as it will calculate the value (DateTime.now()) on run-time and then assign it to our variable and make it constant using final.

Now, what if we try to use const instead of final in the above example?

It throws an error that says:

Const variables must be initialized with a constant value.

Hence, whenever we have a value that we know at compile-time and want it to be constant, we use the const keyword, while if we don’t know the value at compile-time and if it is to be calculated and run-time and want it to be constant, we use the final keyword!

This was a small article but it’s very important how you use const and final keywords based on your requirements!

Hope you enjoyed this article!

If you loved it, you can Buy Me A Coffee!

Don’t forget to connect with me on:

Don’t stop, until you are breathing!💙
- Abhishek Doshi