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 type
void main()
{
// declaring and assigning value to variable a
// of type dynamic
dynamic a = 40;
print(a);
// reassigning value to a
a= "Dart";
print(a);
// reassigning value to a
a= 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 a of dynamic type and assign an integer value to it.
  • Line 8: We print the value.
  • Line 10: We reassign a string value to it.
  • Line 11: We print the value.
  • Line 13: We reassign a float value to it.
  • Line 14: We print the value.

Note: Once a variable is declared as a dynamic type, its value can change over time within the program.

Free Resources