What is a dynamic type in Dart?
Dart dynamic type
In Dart, when a variable is declared as a dynamic type, it can store any value, such as int and float.
The value of a dynamic variable can change over time within the program.
Syntax
dynamic variable_name
Code
The following code shows how to implement the dynamic type in Dart.
// dynamic typevoid main(){// declaring and assigning value to variable a// of type dynamicdynamic a = 40;print(a);// reassigning value to aa= "Dart";print(a);// reassigning value to aa= 10.4;print(a);}
Explanation
Here is a line-by-line explanation of the above code:
- Line 3: We create the
main()function. - Line 7: We declare a variable named
aofdynamictype and assign anintegervalue to it. - Line 8: We print the value.
- Line 10: We reassign a
stringvalue to it. - Line 11: We print the value.
- Line 13: We reassign a
floatvalue to it. - Line 14: We print the value.
Note: Once a variable is declared as a
dynamictype, its value can change over time within the program.