In any programming language, a Variable is a ‘Container’ for storing Data which is same in Dart also.

Variable declaration using the ‘var’ keyword

There are different ways to initialize a variable in Dart. The straight forward and recommended way is by using the keyword ‘var‘.

example:

var personName = 'John Doe';
var personAge = 25;

In the above example, we created a variable with name ‘personName’ and stored the value ‘John Doe’ in that variable. Similarly we created a variable ‘personAge’ and stored 25 value in it.

We use the keyword ‘var’ when we create a variable and we omit the keyword when we use it.

example:

  print(personName); // we get John Doe
  print(personAge); // we get 25

Based on the value assigned into a variable, Dart will automatically infer data type to that variable. In the above example, Dart will automatically give the type of ‘String’ to personName and ‘int’ to personAge.

After initializing a variable with certain type of data using var keyword, it is not possible to assign a different type of data in the same variable later.

Suppose if we try to assign personName = 123  we get the following error message

“A value of type ‘int’ can’t be assigned to a variable of type ‘String'”

Variable Declaration using Data Type in Dart

Instead of using the ‘var’ keyword, we can use the data type to create a variable. The variables in the previous example can also be initialized like this

String personName = 'John Doe';
int personAge = 25;

Many dynamic programming languages such as JavaScript will be able to infer the data types to its variables, but there is no way to explicitly mention the data type to the variables, which we can do in Dart.

Though we are able to give data types to variables explicitly in Dart, it is not recommended. According to the official documentation, they are only annotations and will not get executed during the runtime.

Variable Declaration using ‘dynamic’ keyword

There is another way to create a variable in Dart by using the keyword ‘dynamic‘. As the name suggests, the variable which is created by using the keyword dynamic, can contain any type of data.

example:

dynamic myVar = "Hello World";
myVar = 100; // we can assign a different type data 
myVar = true; // assigning boolean value

One of the major drawback of the most popular programming language in the world JavaScript is the ability to store any type of data in variables. Though it makes programming easy for new developers by writing less code, it will make the large applications very difficult to maintain. That is the reason we have programming languages such as TypeScript, which introduces typing system to JavaScript, thus making the maintenance of large applications less difficult.

We should avoid using the type ‘dynamic’ in Dart unless we do not have any other option.

Leave A Comment

Your email address will not be published. Required fields are marked *