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.
Syntax: datatype variable_name;
Note: Before a variable can be utilized in a program, it must first be declared.
Variables or the identifier must conform to the following rules when declared:
_
and the dollar $
symbol, variable names or identifiers cannot contain spaces or special characters.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.
//declaring and assigning
String name = 'Maria';
int a = "Maria"; // typeError
// A string can't be assigned to a variable of type int
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;
void main() {// Assigning value to variabledynamic myType = "Dynamic type";print(myType);// Reassigning value to variablemyType = 22.0691;print(myType);}
Note: If we use
var
instead ofdynamic
in the code above, it will throw a typeError: a variable of thedouble
type that cannot be assigned to a variable of theString
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
declarationSyntax: final data_type variable_name //with datatype
Syntax: variable_name //without datatype
const
declarationSyntax: const data_type variable_name //with datatype
Syntax: variable_name //without datatype
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
final
orconst
variable can’t be reassigned.