Let’s tear apart this small piece of code.
This might be a Hello World program, but we can actually learn a lot about Dart by tearing apart this code line by line.
Starting off with the word var in the far left-hand side, the word var declares a new variable. This is one way of many in which we can declare a new variable inside Dart. We’ll see other ways too. Right after that, we put variable’s name. In this case, the name of the variable is name. Just like many other programming languages, we can then later on reference the variable by simply writing out the variable name. We then place equal sign and on it’s right-hand side, we have a reference to the function myName(). The set of parenthesis invokes the function and whatever is returned from the function gets assigned to the variable. Also, please note that Dart requires the semi-colon(;) at the end.
On the left-hand side of the equal sign, we have var and name. These two words together form a step called Variable Declaration. It is actually the process of creating a variable and telling Dart that we’ve created a new variable with this name. Then with the equal sign and call to the function, we have a second step referred to as Variable Initialization. It is a process of assigning a value to a variable that has been declared.
Recall the variable initialization process, we had a function call named myName(). Now, let’s take a look at functions in Dart.
Every function we create can have a name, in this case myName. After the name, we place a set of parenthesis which denotes the argument list. So anytime we call a function, we can pass arguments to it. We then have a set of curly braces which forms the function body and inside which we write all the code that needs to be executed every time the function is called. What’s interesting is the word String before the function name. So anytime our function returns a value, we can annotate that function with the type of value that is going to be returned, in this case String because that is the type of value we are going to return.
We can give our function any name with just one exception, main. In Dart, the main function is very special function that has to be defined in every program that we put together. It is automatically invoked anytime our program is executed. So, basically the flow of program is like:
First of all, the program starts up and the main function is executed. The main function then executes the rest of the code. If there is no main function, we encounter error.