If a variable is declared as dynamic, its type can change over time.
dynamic a = 'abc'; //initially it's a string
a = 123; //then we assign an int value to it
a = true; //and then a bool
If you declare a variable as a var, once the assigned type can not change.
var b = 'cde'; //b is a string, and its type can not change
b = 123; //this will not compile
//can not assign an int to the string variable
This declares a variable
b
and assigns it the string value'cde'
using thevar
keyword. Sincevar
is a dynamic type, the type of the variableb
is inferred to beString
based on the value it is initialized with.Next, the code attempts to reassign the variable
b
to the integer value123
. However, this will result in a compile-time error because the typeb
is already inferred to beString
based on its initial value, and aString
variable cannot hold an integer value.In Dart, variables with an inferred type are statically typed, which means that their types are checked at compile time. This is different from dynamically typed languages like JavaScript, where variables can change types at runtime.
Therefore, attempting to assign a value of an incompatible type to a statically-typed variable will result in a compile-time error, as we see in this example.
But, if you state a var without initializing, it becomes dynamic:
var a; //this is actually a dynamic type
a = 2; //assigned an int to it
a = 'hello!'; //assigned a string to it
print(a); //prints out 'hello'
declares a variable
a
using thevar
keyword without specifying its type, which means that it will be inferred as adynamic
type. Adynamic
type in Dart allows variables to hold values of any type, and the type is determined at runtime.Next, the code assigns the integer value
2
to the variablea
. Sincea
is of typedynamic
, it can hold values of any type, including integers.Then, the code assigns the string value
'hello!'
to the same variablea
. Again, sincea
is of typedynamic
, it can hold values of any type, including strings.Finally, the code prints the value of the variable
a
using theprint()
function, which outputs the string'hello!'
to the console.Since the type of
a
is dynamic, Dart does not perform any type of checking on the values assigned to it. This means that it is possible to assign values of different types to the same variable during runtime, as we see in this example. However, usingdynamic
excessively can make your code less type-safe and harder to debug, so it's generally recommended to use more specific types whenever possible.