
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Final Keyword in Dart Programming
The final keyword in Dart is used to create constants or objects that are immutable in nature. The only difference between the final and const keyword is that final is a runtime-constant, which in turn means that its value can be assigned at runtime instead of the compile-time that we had for the const keyword.
Example
Consider the example shown below −
void main(){ final int xy = 10; print(xy); }
Output
10
In the above example, we declared an int variable with a final keyword, which means that the value once assigned to it won't change.
Example
Consider the example shown below −
void main(){ final int xy = 10; print(xy); xy = 99; print(xy); }
Output
Error: Can't assign to the final variable 'xy'. xy = 99; ^^ Error: Compilation failed.
Like any normal variable in Dart, the variable declared with the final keyword can also infer the type of data it is going to store with the help of dartAnalyzer.
Example
Consider the example shown below −
void main(){ final name = "tutorialspoint"; print(name); }
Output
tutorialspoint
Now let's have a look at the case where the value is evaluated at runtime.
Example
Consider the example shown below −
void main(){ final squareOfTwo = getSquareOfNumber(2); print("SqaureOfTwo = $squareOfTwo"); } num getSquareOfNumber(num i){ return i * i; }
In the above example, we have the main function inside which the final constant is getting its value from a function that will be evaluated at runtime and not compile-time.
Output
SqaureOfTwo = 4