What is Dynamic Keyword In Dart?, and it use? | Constants in Dart| Dart-Constants| Dart Tutorial #4
Dynamic In Dart
In Dart, Dynamic Keyword is used to assign different data type to a variable if we dont declare it Dynamically. It is Very Usefull Feature in Dart as we Can store any type of value in it. For eg Float,Int,Boolean Etc. The Value of Dynamic can Change overtime within the Program. Lets see it Syntax and Code.
Synatax
dynamic name_of_Variable
Code
void main() { dynamic a=10; print(a); a=5.5; print(a); a="Rahul"; print(a); a=true; print(a); }
Output
10 5.5 Rahul true
Now We Have Understood The concept of Dynamic Keyword in Dart. Lets Now mood forward to Constants In Dart.
Constants in Dart
Contants Is the Value which Does Not Change at Any interval of time. It is Defined Before Runtime. Contants Holds very Important role in Any Programing Language as it helps to Big programs without changing its Values. In Dart We Also Define Contant. When we Develop a Program we want some values should Remain Same through out the Whole Program, for Eg:- Value of PI(Ï€) i.e 3.14 or 22/7.
In Dart There are Two ways of Declaring a Contant:-
- Final Keyword
- Const Keyword
Final Keyword
If We Use "final" keyword, the Memory is not assigned until we use it in any function or it does not take memory initially. The Memory will be Assigned only if we use it in any funtion and its value will be assigned to the Memory at the Runtime. Lets see code and Syntax of It.
Syntax
// Without any DataType final Name_of_varibale; //With data type final data_type name_of_variable
void main() { final a="Bob"; print(a); }
Const Keyword
If We use "Const" Keyword, the memory is assigned. It does Not matter if we use it or not, it will take space in memory. The main difference between the Const Keyword and Final keyword is that the memory is assigned first and on the other hand the Memory is assigned at the Time of Runtime.
// Without any DataType const Name_of_varibale; //With data type const data_type name_of_variable
void main() { const a="Bob"; print(a); }
Instance Variable
Intance Varibale can be Final but cannot be Constant. Instance Varibale is a Variable that is Declared inside the Class. We Cannot use Const Keyword Inside a Class, if we want to use it, we have to use a Keyword which is "Static". Use of Static keyword before Const keyword can fix the error.
void main() { class a{ final n=2; const n=5; //It will Throw an Error } }
void main() { class a{ final n=2; static const n=5; //Now There Will be no erro } }