Hi Guys, Welcome to Proto Coders Point, In this dart tutorial we will learn what is the difference between final and const keyword in flutter dart.
Even dart programming language support assigning a constant value to a dart variable, Here constant value means once a value is assigned to the variable then it cannot be altered/changed.
There are 2 keywords used to declare constant variable in dart:
- const keyword.
- final keyword.
Const Keyword in dart
The const keyword in dart, are similar to final keyword but, The only different between const & final is, In const variable initialization can only be done during compile-time, means a variable value cannot be initialized at run-time.
Example:
String name;
//get input to name from user
name = stdin.readLineSync();
//you will get error; doing this
const copyname = name; //error
In Simple words, by using const keyword you cannot take input from user and then assign to const variable in run-time. but by using const you can assign value directly at compile-time only.
Example:
const number = 85785;
// later this can't be changed; like this
number = 854; // cant do this
When to use const keyword
Suppose you have a value that will never alter or should not be changed during run-time. Eg: A String ‘ProtoCodersPoint’ will always be same for a app name, but if you are integrating a time in your app then const should not be used for currect time because it keep change every milli seconds.
final keyword in dart
In final keyword, the only different i we can assign a value to final variable at run-time(but only once), that means we can assign value to final keyword by taking manual input from user, but once value is been assigned then cannot be altered.
Example
final int? number;
number = int.parse(stdin.readLineSync());
Print(number);
//Now number is already assigned.
//then it can’t be altered again like this;
number = 100; // Error: Not Possible to change the value.
Example on final & const keyword
void main(){ finalvariable(500); constvariable(5); } void finalvariable(int value){ final finalvariable = value; print(finalvariable); //finalvariable = 5000; // this is not possible } void constvariable(int value){ const directinit = 100; print(directinit); // const variableconst = value; // after compile time, initializing value to const variable is not possible }