var
typeIn Dart, when a variable is declared as a var
type, it can hold any value such as int
and float
.
The value of a var
variable can not change within the program once it is initialized at declaration.
var variable_name
The following code shows how to implement the var
type in Dart.
void main() {var a; // declaring a variable of type vara = 40; // initializing variable aprint(a);a = "Dart"; // reassigning string value to `a`print(a);a = 10.4; // reassigning float value to `a`print(a);}
Line 1–11: We create the main()
function. Within the main()
, we have the following:
Line 2: A variable named a
of var
type.
Line 3: We assign an integer
value to it.
Line 4: We print the value of a
.
Line 6: We reassign a string
value to it.
Line 7: We print the value of a
.
Line 9: We reassign a float
value to it.
Line 10: We print the value of a
.
Let’s try initializing at the point of declaring the variable and then reassigning a value to it.
Note: The following code will throw an error.
void main() {var a = 40;print(a);a = "Dart";print(a); // Error: A value of type 'String' can't be assigned to a variable of type 'int'}
If we initialize a variable of type var
at the point of declaration, we can’t reassign a value to it.