- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
const keyword in Dart Programming
Dart provides us with two ways in which we can declare variables with fixed values. One of them is by declaring a variable with a const keyword, and the other is by declaring the variable with a final keyword.
It should be noted that both of them does provide an assurance that once a value is assigned to the variable with them, it won't change, but indeed they are slightly different from one another.
const
A variable that is declared using the const keyword cannot be assigned any other value. Also, the variable is known as a compile-time constant, which in turn means that its value must be declared while compiling the program.
Example
Consider the example shown below -
void main(){ const name = "mukul"; print(name); const marsGravity = 3.721; print(marsGravity); }
Output
mukul 3.721
If we try to assign any other value to any of the two variables declared above, the compiler will throw an error.
Example
Consider the example shown below -
void main(){ const name = "mukul"; print(name); name = "mayank"; print(name); }
Output
Error: Can't assign to the const variable 'name'. name = "mayank"; ^^^^ Error: Compilation failed.
It should also be noted that we can declare Objects at compile-time and assign them to a constant variable.
Example
Consider the example shown below −
import 'dart:math'; void main(){ const Rectangle bounds = const Rectangle(0, 0, 3, 4); print(bounds); }
Output
Rectangle (0, 0) 3 x 4
- Related Articles
- final keyword in Dart Programming
- Super keyword in Dart Programming
- This keyword in Dart Programming
- Comments in Dart Programming
- Constructors in Dart Programming
- Enumerations in Dart Programming
- Functions in Dart Programming
- Immutability in Dart Programming
- Inheritance in Dart Programming
- Iterables in Dart Programming
- Lists in Dart Programming
- Loops in Dart Programming
- Maps in Dart Programming
- Methods in Dart Programming
- Mixins in Dart Programming
