Your First Dart Program
In the last chapter you learned what Dart is and how to install it. Now it is time to make your computer run a program you wrote. This chapter walks through that whole loop: create a file, run it, understand what every line means, and fix the mistakes that almost everyone makes at first.
We assume no background beyond everyday computer use. Every technical word will be explained as we go.
The smallest useful program
Dart programs start running at a function called main. A function is a named piece of code that does a job. Every Dart program must have a main, because that is where the computer is told to begin.
Create a new folder on your computer. Inside it, make a file called hello.dart. The .dart ending tells tools the file holds Dart code. Type this into the file:
void main() {
print('Hello, world!');
}Now open a terminal. A terminal is a window where you type commands for your computer instead of clicking icons. Move into the folder you made, then type:
dart run hello.dartYou should see:
Hello, world!That is it. You have written and run a real program. Let us take the file apart, line by line, because every piece of it matters.
Reading the program line by line
void main() {
print('Hello, world!');
}voiddescribes what the function gives back when it finishes.voidmeans "nothing." This function does its work and hands nothing back.mainis the name. Dart looks for exactly this name to start your program. If you spell itMainormain2, the program will not start.()is the list of inputs to the function, called parameters.mainhere takes no inputs.{and}are braces. They mark the boundaries of the function's body, the code it will run. Everything between them belongs to the function.print('Hello, world!');tells Dart to display the text between the quotes.printis a built-in function that comes with Dart, so you do not need to install anything to use it. The semicolon at the end ends the statement, a bit like the period at the end of a sentence. Forgetting it is the most common beginner mistake.
Text in quotes, like 'Hello, world!', is called a string. Strings hold words, sentences, and symbols.
A slightly bigger program
A program that only prints one line does not show much. Here is a version that does a tiny bit of work:
void main() {
var name = 'Ada';
var year = 205;
print('Happy birthday, $name!');
print('You are about $year years old.');
}Run it with dart run hello.dart again and you will see two lines of output.
Two new ideas appear here.
First, var name = 'Ada'; creates a variable. A variable is a named box that holds a value so you can use it later. var tells Dart "figure out the type yourself." Since we put text in the box, Dart treats name as holding a string.
Second, '$name' inside the print line does string interpolation. Interpolation means "insert the value of a variable into text." The dollar sign followed by a variable name is replaced by that variable's value when the line runs. If you need a calculation inside text, wrap it in braces, like '${year + 1}'.
Program structure: files and libraries
Real programs are more than one file. Dart programs are made of libraries. A library is simply a Dart file whose code other files can use. You connect files with the import keyword.
Make a second file called greet.dart in the same folder:
String makeGreeting(String who) {
return 'Hello, $who!';
}Then change hello.dart to use it:
import 'greet.dart';
void main() {
print(makeGreeting('Grace'));
}The import 'greet.dart'; line pulls in the code from the other file so main can call makeGreeting. Running dart run hello.dart still works the same way: you always name the file that contains main, and Dart follows the imports from there.
Show diagram source
flowchart TD
A["dart run hello.dart"] --> B["Load hello.dart"]
B --> C["Find main()"]
C --> D["Follow imports: load greet.dart"]
D --> E["Call makeGreeting('Grace')"]
E --> F["Return 'Hello, Grace!'"]
F --> G["print the result"]Running programs two ways
Dart gives you two main ways to run your work, and knowing when to use each is a useful habit.
dart run hello.dartruns the file right away, translating it as it goes. This is the fast loop you want while learning and experimenting. Changes show up the moment you rerun.dart compile exe hello.dartturns your program into a standalone file that runs without Dart installed. You would do this when sharing a finished program with someone who does not have the Dart tools.
There is a third mode worth knowing about: the Dart VM (a VM, or virtual machine, is the engine that actually executes Dart code) also runs your program in a "just-in-time" way, meaning it translates hot code paths while running for speed. You do not control this directly; it happens automatically.
What the analyzer does for you
When you run a Dart program, a helper called the analyzer looks over your code first. The analyzer checks spelling, matching braces, missing semicolons, and type mistakes before anything runs. If you type print('hi') with no semicolon, you get a clear message pointing at the line, like:
Error: Expected ';' after this.Treat these messages as help, not scolding. They name the file, the line, and the problem. Most of your early debugging (debugging means finding and fixing mistakes) will be reading these messages and looking at the exact line they point to.
Good habits for your first week
- One idea per line, and let the braces show structure. Indent the code inside
{ }by two spaces, the common Dart style. - Name variables after what they hold:
year, noty. - When something confuses you, print it.
printis your cheapest debugging tool. - Keep programs small while learning. A file you can read in one screen is a file you can fix.
Where you are heading
You can now create a Dart file, run it, read its parts, and split code across files. Next comes the language itself: variables, types, and how Dart decides what kind of value each variable holds.
Exercise
What happens if you run dart run hello.dart but the file hello.dart does not contain a function named main?
Show answer
The program fails to start. Dart always looks for main as the entry point, so the tool reports an error telling you it could not find a main function to run.
Exercise
In the line print('Hello, $name!'), why does name not appear as the literal text "$name" in the output?
Show answer
The dollar sign starts string interpolation. Dart replaces $name with the current value of the variable name when the line runs, so the output shows the value, not the text.
Spotted a mistake, or code that does not work?