Dart – Variable

Variable is used to store the value and refer the memory location in computer memory. When we create a variable, the Dart compiler allocates some space in memory. The size of the memory block of memory is depended upon the type of variable. To create a variable, we should follow certain rules. Here is an example of a creating variable and assigning value to it.

var name = 'Devansh';

Here the variable called name that holds ‘Devansh’ string value. In Dart, the variables store references. The above variable stores reference to a String with a value of Devansh.

Rule to Create Variable

Creating a variable with a proper name is an essential task in any programming language. The Dart has some rules to define a variable. These rules are given below.

  • The variable cannot contain special characters such as whitespace, mathematical symbol, runes, Unicode character, and keywords.
  • The first character of the variable should be an alphabet([A to Z],[a to z]). Digits are not allowed as the first character.
  • Variables are case sensitive. For example, – variable age and AGE are treated differently.
  • The special character such as #, @, ^, &, * are not allowed expect the underscore(_) and the dollar sign($).
  • The variable name should be retable to the program and readable.

How to Declare Variable in Dart

We need to declare a variable before using it in a program. In Dart, The var keyword is used to declare a variable. The Dart compiler automatically knows the type of data based on the assigned to the variable because Dart is an infer type language. The syntax is given below.

Syntax :-

var <variable_name>  = <value>;  

OR

var <variable_name>;

Example :-

var name = 'Andrew';

Declaring the variable with Multiple Values

Dart provides the facility to declare multiple values of the same type to the variables. We can do this in a single statement, and each value is separated by commas. The syntax is given below.

Syntax –

<type> <var1,var2....varN>;  

Example –

int i,j,k;

Leave a comment

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