Dart Programming Tutorial 1.2 - Using Variables
-Last updated Wednesday, March 27, 2013
In computer programming, a variable is basically a name you give to a piece of the computer's memory. Think of memory as a bunch of boxes that contain data and a variable as one of those boxes. When you ask the processor to give you the information in box A, he'll go to the computer's "warehouse" (memory) and open box A.
Declaring a variable
Creating a variable in Dart is extremely easy. Here's a simple example:
var text='Hello World!';
In the above example, we tell Dart to create a variable using the var keyword. This variable is named 'text' and contains "Hello World" as data.
We can also use variables to store numbers:
var number=9;
Using variables in a command
Remember our "Hello World" program from the last tutorial?
void main() { print("Hello World"); }
Let's rewrite it so that we use a variable to hold the text we want to print. The first thing we need to do is to create this variable and assign it some text:
var text = "Hello World";
Now, we can change our Print command so that it outputs the content of this variable instead of a predetermined line of text:
print(text);
So now, our Hello World program looks like this:
void main() { var text = "Hello World"; print(text); }
If we had wanted to, we also could've written:
var text = 1;
In which case our program's output would've been, you guessed it: 1
Now I'm sure you're wondering: what's the point of variables here? It makes the program longer and more complex! Well, in reality, this is just a simple example to show you how to use Dart variables; in real world programs (which we will write further on in this tutorial), variables have a HUGE role.
Next Tutorial, Conditional Statements-->