In this chapter, we will learn about Dart variables and constants in dart, how to declare and initialize them.
Variable is an identifier that stores data. For example,
var name = “Jackson”;
Here name is a variable that stores the string data Jackson.
To declare variables, keyword var is used. For example,
Dart also supports type-checking which helps in declaring the variables. For example,
int number; // for integer values String name; // for string values
To assign a value to variables, the assignment operator (=) is used. For example,
var number = 5;
Here number is a variable and value 5 is assigned to the number variable.
Similarly we can pass specific values to the variables. For example,
String name = “Lauren”;
If we try to pass integer values to string variable, then we get the error.
String name = 4; // Error: A value of type 'int' can't be assigned to a variable of type 'String'.
Changing values of variables
The variables mean that the values can be changed. We can simply change the value of a variable by assigning a new value to the variable.
var name = ‘Sam’; name = ‘John’;
Rules for naming a Dart variable
- Variable names can consist of numbers and alphabets, underscore (_) and the dollar ($) sign. For example,
var name = ‘Sam’; var $name = ‘Pam’; int number = 4.4;
- Variable names cannot contain keywords. For example,
var void = ‘Sam’;
- Variable names should be alphabet and cannot start with numbers. For example,
var 2name = ‘Sam’;
- Dart is case-sensitive. Hence a and A are different. For example,
var a = ‘Sam’; var A = ‘Smith’;
A is not equal to a.
Dart constants are similar to the dart variables. They are used to store values. The only difference is that the values of a constant cannot be changed afterwards.
The constants are denoted by the keyword final and const. For example,
final name = ‘Sam’; const number = 500;
We will learn about Dart Operators in the next chapter.