What are variables in Dart programming?

Variables is a type of identifier that refers to a memory address in a computer’s memory that maintains a value for that variable. This value can be updated throughout the program’s execution. When you declare a variable in Dart, you are allocating memory for that variable. The size of the memory space allocated and the type of the value it holds entirely depend on the type of variable.

Declaration

Syntax: datatype variable_name;

Note: Before a variable can be utilized in a program, it must first be declared.

Rules

Variables or the identifier must conform to the following rules when declared:

  1. The keyword cannot be a variable name or an identifier.
  2. A variable name or identifier can contain alphabets and integers
  3. Except for the underscore_ and the dollar symbol, variable names or identifiers cannot contain spaces or special characters.
  4. A number cannot be the first character in a variable name or the identifier.

Note: Dart supports type-checking, which means it determines whether the data type and data that are stored by a variable are unique to that data.

Example

//declaring and assigning
String name = 'Maria'; 

int a = "Maria"; // typeError
// A string can't be assigned to a variable of type int

Dynamic type variables

dynamic creates a specific variable called dynamic. During the program’s execution, the variable declared with this data type can store any value implicitly. It’s comparable to the var datatype in Dart. However, the distinction is that when you assign data to a variable using the var keyword, the appropriate data type is changed.

Syntax: dynamic variable_name;

Code

void main() {
// Assigning value to variable
dynamic myType = "Dynamic type";
print(myType);
// Reassigning value to variable
myType = 22.0691;
print(myType);
}

Note: If we use var instead of dynamic in the code above, it will throw a typeError: a variable of the double type that cannot be assigned to a variable of the String type.

final and const

In Dart, the keywords final and const are used to define constant variables. This means that once a variable is defined using these keywords, its value cannot be modified throughout the code. These keywords can be combined with or without the name of a data type.

final declaration

Syntax: final data_type variable_name //with datatype

Syntax: variable_name //without datatype

const declaration

Syntax: const data_type variable_name //with datatype

Syntax: variable_name //without datatype

Code

The code below shows the use of the final and const keywords in Dart programming:

void main() {
// const variable
const myType = "const type";
print(myType);
// final variable
final myType1 = "final type";
final String myType2 = "final type !!!";
print(myType1);
print(myType2);
}

Note: A final or const variable can’t be reassigned.

Free Resources