Dart Variables

Dart is type-safe. So, most variables does not require explicit type declaration.

Create a Variable

You can create a variable using var keyword.

var a;

As no value is assigned to the variable, and we did not mention the type explicitly, the type of variable would be Null and the value stored would be null.

ADVERTISEMENT

Assign Value to Variable

You can assign a value to the variable using assignment operator =.

var a = 'Hello World';

Variables store references to the actual value. In the above example, variable a stores the reference to the String object 'Hello World'.

If you assign a value to variable, the type of the variable would be inferred from the value.

Explicit Declaration

You can explicitly declare the type of variable instead of var keyword.

String a = 'Hello World';

Re-assign Variable with value of Different Datatye

Using dynamic keyword, you can reassign a variable with different datatype from the one that it is actually referencing.

void main(){
	dynamic a = 'Hello World';
	a = 10;
}

Conclusion

In this Dart Tutorial, we learned how to declare and initialize variables, inference and explicit declaration.