What is the difference between const
and final
keyword in Dart?
The difference between the “const” and “final” keywords in Dart
constantsdartfinalkeyword
Related Topic
- The difference between char * const and const char *
- Java – What does ‘synchronized’ mean
- C++ – the difference between const int*, const int * const, and int const *
- Javascript – the purpose of the var keyword and when should I use it (or omit it)
- C++ – Difference of keywords ‘typename’ and ‘class’ in templates
- C++ – Difference between `constexpr` and `const`
- R – Drupal JSON POST from PhoneGap
- C# – To get controls inside static function
Best Answer
There is a post on dart's website and it explains it pretty well.
Final:
Const:
So, what does this mean?
Const:
If the value you have is computed at runtime (
new DateTime.now()
, for example), you can not use a const for it. However, if the value is known at compile time (const a = 1;
), then you should useconst
overfinal
. There are 2 other large differences betweenconst
andfinal
. Firstly, if you're usingconst
, you have to declare it asstatic const
rather than justconst
. Secondly, if you have aconst
collection, everything inside of that is inconst
. If you have afinal
collection, everything inside of that is notfinal
.Final:
final
should be used overconst
if you don't know the value at compile time, and it will be calculated/grabbed at runtime. If you want an HTTP response that can't be changed, if you want to get something from a database, or if you want to read from a local file, usefinal
. Anything that isn't known at compile time should befinal
overconst
.With all of that being said, both
const
andfinal
cannot be reassigned, but fields in afinal
object, as long as they aren'tconst
orfinal
themselves, can be reassigned (unlikeconst
).