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:
- The keyword cannot be a variable name or an identifier.
- A variable name or identifier can contain alphabets and integers
- Except for the underscore
_and the dollar$symbol, variable names or identifiers cannot contain spaces or special characters. - 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 variabledynamic myType = "Dynamic type";print(myType);// Reassigning value to variablemyType = 22.0691;print(myType);}
Note: If we use
varinstead ofdynamicin the code above, it will throw a typeError: a variable of thedoubletype that cannot be assigned to a variable of theStringtype.
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 variableconst myType = "const type";print(myType);// final variablefinal myType1 = "final type";final String myType2 = "final type !!!";print(myType1);print(myType2);}
Note: A
finalorconstvariable can’t be reassigned.