Your First Dart Program
Every Dart program starts at a function called main. A function is a named block of code that does a job. Dart looks for main and runs whatever is inside it. Think of it as the front door of your program.
A Tiny Program
Here is the classic first program. Save this in a file called hello.dart:
void main() {
print('Hello, Dart!');
}Let's take it apart piece by piece:
voidmeans this function gives back no result. It just does work.mainis the special name Dart uses as the entry point.- The parentheses
()are where inputs to the function would go. There are none here. - The curly braces
{ }hold the body, the list of steps to run. print(...)displays text on the screen. Each statement ends with a semicolon.
Running It
Open a terminal (the command line tool on your computer), go to the folder with your file, and type:
dart run hello.dartYou should see Hello, Dart! appear. That is your first working program. If dart is not found, the previous chapter covers installing the Dart SDK, the toolkit that provides this command.
Doing a Little More
Programs get interesting when they store values and make choices. A value stored with a name is called a variable:
void main() {
var name = 'Ada';
var year = 1815;
print('$name was born in $year.');
if (year < 2000) {
print('Born in the 20th century or earlier.');
} else {
print('Born in the 21st century.');
}
}The word var tells Dart "make a variable and figure out its type from the value." A type describes what kind of data it is, like text (String) or whole numbers (int). You do not have to spell types out; Dart can infer them, which means it works them out for itself.
The line '$name was born...' uses string interpolation. When text is in single quotes and a $ appears before a variable name, Dart replaces it with that variable's value. To put a literal dollar sign in your text, escape it as \$.
The if and else lines are a branch: the program picks one path based on a yes-or-no question.
Program Structure at a Glance
Show diagram source
flowchart TD
A[main function] --> B[Create variables]
B --> C[print statement]
C --> D{if condition true?}
D -->|yes| E[run first block]
D -->|no| F[run else block]A program can also have other functions beside main, and main can call them. We will build up to that in later chapters. For now, everything lives inside main, which keeps things simple while you learn the shape of the language.
Exercise
What does the word void mean at the start of main?
Show answer
It means the function returns no value to whoever called it. It performs its work, such as printing, and finishes without handing back a result.
Exercise
In print('$name was born in $year.'), what do the dollar signs do?
Show answer
They mark interpolation. Dart replaces $name and $year with the current values of those variables before printing the text.
Spotted a mistake, or code that does not work?