Difference between "var" and "dynamic" type in Dart?

Difference between "var" and "dynamic" type in Dart?

Flutter Basic Questions

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 the var keyword. Since var is a dynamic type, the type of the variable b is inferred to be String based on the value it is initialized with.

  • Next, the code attempts to reassign the variable b to the integer value 123. However, this will result in a compile-time error because the type b is already inferred to be String based on its initial value, and a String 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 the var keyword without specifying its type, which means that it will be inferred as a dynamic type. A dynamic 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 variable a. Since a is of type dynamic, it can hold values of any type, including integers.

  • Then, the code assigns the string value 'hello!' to the same variable a. Again, since a is of type dynamic, it can hold values of any type, including strings.

  • Finally, the code prints the value of the variable a using the print() 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, using dynamic excessively can make your code less type-safe and harder to debug, so it's generally recommended to use more specific types whenever possible.