All lessons

Your First Program

5 min · Dart

Write and run your very first Dart program, right here on the page.

Dart · Your First Program0/5 cleared

Enemy 1 of 5

Every Dart program starts in main

Every Dart program starts running inside main. This example uses print to show the text Hello, World! on its own line. Press Run to see it.

Why this works

Unlike scripting languages that run top to bottom the instant you open the file, Dart requires a specific entry point: a function called main. When you run a Dart program, the very first thing that executes is the code inside main(). Everything the program does flows from there, directly or indirectly. This is similar to how languages like Java, C, and C++ work, and different from PHP or Python, where code at the top level of a file just runs in order without needing a named entry function.

void main() { ... } breaks down into three parts: void tells Dart this function doesn't hand back a value when it finishes (as opposed to a function that computes and returns something), main is the required name Dart looks for, and the curly braces { } contain the block of code that runs when the program starts.

print() is Dart's basic tool for writing a line of text to the output. It takes one argument (the value to display) automatically converts it to text if it isn't already a string, and adds a newline after it, so consecutive print() calls each land on their own line.

Every statement inside the braces ends with a semicolon (;), matching the C-family style Dart borrows its syntax from. A missing semicolon is one of the most common first errors. Dart's error message will often point near where it expected one, which is a good habit to check first when something doesn't compile.

You
Binary Treant
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.