We are familiar variables in dart, which we usually declare with var keyword or we can declaring them using type annotation. Guess what? There is another type, which ensures integrity of your data, you can call such variables 'immutable variables' or in a simple word 'constants'.
We'll be discussing two ways of declaring constants in Dart:
- 'const' keyword
- 'final' keyword
'const' Keyword
First of all let's look at the syntax:
const num hoursSinceMidnight_with_const = 2;
print('Hours : $hoursSinceMidnight_with_const');
const value is detected on compile time. Its value will be immutable in the entire program and you will not be able to change its value anywhere in the program. If you try to modify value anywhere in the code, that'll generate error.
'final' Keyword
Let's talk about another way to create constant with final keyword. When we use final, value is detected during runtime and after that point it can't be changed.
Now compare this code snippet with the const code above:
const hoursSinceMidnight = DateTime.now().hour;
print('Hours before midnight: $hoursSinceMidnight');
Above code will generate error because when we run it, at runtime we'll be attempting to set a value to hoursSinceMidnight constant, which will end up generating an error. If we you are using VS code editor then it will show you error.
Let's change our code a bit, we'll be replacing const with final keyword.
final hoursSinceMidnight = DateTime.now().hour;
print('Hours before midnight: $hoursSinceMidnight');
That's about it, have a good day 😊
Top comments (0)