Variables in Dart

Using our previous example that prints out some text to the output console, lets now create a variable to store the text, so we can re-use it.

void main() {
  var a = 'Hello World';
  print(a);
  print(a);
}

The above should print out two instances of the text “Hello World”, instead of just one. Instead of having the full longer text duplicating for each print() statement, we can store the full text in a variable we called “a” and then tell the program to print out what is stored in the variable.

Every time you create a variable, you need to use the keyword “var” at the beginning to indicate that it is a variable that you are creating. You can name your variables nearly anything you would like, as long as follows the following languages rules:

  • cannot be keywords
  • cannot have spaces or special character, except
  • underscores (_) and dollar signs ($)
  • cannot begin with a number

Here are a few examples of valid variable names:

void main() {
  var a = 'My variable a';
  print(a);
  var b = 'My variable b';
  print(b);
  var myVar = 'My variable myVar';
  print(myVar);
  var my_var = 'My variable my_var';
  print(my_var);
  var myVar3 = "My variable myVar3";
  print(myVar3);
}

You only need to use the keyword “var” at the beginning the first time you are creating and initializing the variable. Then after that you can leave off the keyword “var” and can also reassign or give the variable a new value or make it store something else that is similar, like this:

// This Dart program prints the first value of the variable "a" and then gives the variable "a" new value. Then it prints the new value too.

void main() {
  var a = 'First text';
  print(a);
  a = 'Second text';
  print(a);
}

When you create a variable in the Dart language, it automatically tries to recognize the type of variable you are trying to create, so in the example below, it set the type of variable to the type of “Text String”. This means that you can use that variable to store any text string you want, but will get an warning or error if you try to store something else that is not text in that same variable, as shown below:

void main() {
  var a = 'Some text';
  a = 7;
}
// Gives an error!

The above results in an error explaining that you cannot put a integer/number type value in a variable that is of a text string type. The text variable can only store text. This is why the Dart programming language is considered a statically typed language.

If you assign a number value to the variable “a”, then the variable will automatically be set to a “Number” type and will allow you to store any numbers in it. Go ahead and try this out and you should see it print out the two numbers:

void main() {
  var a = 100;
  print(a);
  a = 200;
  print(a);
}

You can also assign the resulting number of an mathematical equation as the number value the variable should store, like the this:

void main() {
  var a = 50 + 100;
  print(a);
}
// This Dart code prints 150 to the output console.

You can accomplish the same thing, by putting the equation in the print statement as well, like this:

void main() {
  var a = 50;
  print(a + 100);
}
// This Dart code also prints 150 to the output console.

It is worth experimenting with different types of numbers and combinations of where things are, to get understand how the results can be quite different, such as the following with negative and positive floating point numbers:

void main() {
  var a = -50.99;
  print(a + 100);
  // Result: 49.01
  
  var b = 50.99;
  print(b + 100);
  // Result: 150.99
}

Another option is to explicitly set the variable type to what you want it to be, instead of relying on the automatic variable type assignment to be inferred (type inference). The following explicitly set the variable type of “a” to text string type and if you try to store a number in it, you will get an error.

void main() {
  String a = 50;
  print(a);
}

But, if you put single or double quotes around the variable values to make them text strings, then it will print out the text to the console just fine. As well, you can add to string variables together like below, which is called string concatenation.

void main() {
  String a = 'The number ';
  String b = "3";
  print(a + b);
  // Result: The number 3

  String c = a + b + " is my favorite number.";
  print(c);
  // Result: The number 3 is my favorite number.
}

You can also insert variables directly inside the text string values, like the following (which is referred to as string interpolation).

void main() {
  String fruit = 'apple';
  print("Please eat an $fruit everyday.");
}
// Result: Please eat an apple everyday.

One other thing you can do that is probably worth noting at this point, is the ability to make a dynamic variable. So, if you create a variable named “a” and assign it a text string, it will be set to as a text type, but then if you re-assign it a number value, the variable type will automatically change to a number type.

void main() {
  dynamic a = "Some text";
  print(a);
  // Result: Some text

  a = 333;
  print(a);
  // Result: 333
}

Another example is when you are working with two different type of numbers and if you try to something like below, you will get an error, because the variable is automatically set as a integer number with no decimal.

void main() {
  var x = 3; // x is inferred as an int
  x = 4.0;
  print(x);
  // Gives an error!
}

So, one way to solve this is to make the variable dynamic, so that it will change the variable type after it creates and initializes the variable. In this case, from a double to an integer number type.

void main() {
  dynamic x = 4.5;
  x = 3;
  print(x);
}
// Result: 3

It is considered best practice to only use dynamic variables, if you don’t know what the variable type is going to be when it is initialized. Utilizing statically typed code can lead to code that is easier to use, safer and less error-prone.

If you know the variable type, then it is better to explicitly set the variable type as a number, so that you be sure your variable will stay some sort of number and not change to a text string, like this:

void main() {
  num x = 4.5;
  x = 3;
  print(x);
}
// Result: 3

Some variable types are more specific like double and integer (int), while other variable types like number (num) can be assigned an integer or a double number.

void main() {
  double a = 1.5;
  int b = 1;
  num c = 1.5;
  num d = 1;
  print(a + b + c + d);
  // Result: 5
}

It is good to be award that variables that are not assigned a value (uninitialized) but are created/declared and then used, will result in a null value, which essentially means that nothing is being stored in the variable, as illustrated below:

void main() { 
   var a; 
   print(a); 
}
// Result: null

There are also keywords that you can use when creating a variable to restrict the use of that variable, such as not allowing the variable’s value to be changed after first created or initialized. One such keyword is “final”, which makes it so the variable can only be assigned a value one time (single-assignment), so once the variable is initialized, the variable’s value cannot be changed. And, if you try to change the variable’s value, then you will get an error saying a final variable can only be set once, as illustrated below:

void main() { 
   final a = 3;
   print(a);
   a = 6;
}
// Result: Error!

When you use keywords such as final, it changes the mutability of the variable, meaning that if the keyword final is used, then the variable will be immutable. If the variable using the var keyword then it will be mutable.

void main() { 
  var a = 3;
  // The a variable is mutable, so its value can change.

   final b = 6;
  // The b variable is immutable, so its value can not change.
}

If you know that a variables value is not going to change, then it is usually best to make the variable immutable whenever possible, as a best practice.

To review the basic structure of a variable statement, lets look at the basic anatomy of the following text string variable assignment statement.

String fruit = 'apple';
  • The left side of the equal sign is the variable declaration:
    • String is the variable type
    • name is the variable name
  • The rest of the statement is the variable initialization:
    • = the equal sign indicates assignment
    • ‘apple’ is a string literal or the value
    • ; the semicolon is the terminator ending

Here is some additional notes on variables in Dart:

  • variables are named spaces in computer memory
  • variables act as containers to store values
  • variable names are called identifiers
  • variables must be declared before they can be used
  • variables in Dart store a reference to the value, rather than containing the value
  • variables have an initial value of null
  • the Dart language considers all values as objects