Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 61 ยท Getting Started

Your First Dart Program

Write your first Dart program: the main function, print, comments, string interpolation and the basic structure every Dart file follows, with runnable stand-ins.

Every Dart program starts the same way: the runtime looks for a function named main and calls it. That single rule is the foundation of everything else in this lesson. You will write a short program, learn how print and string interpolation work, see the three kinds of comments, and understand how a file is organized.

The Dart snippets below are read-only. After each important idea there is a TypeScript stand-in you can run and edit, so you can feel how it works even though the site cannot run Dart.

The smallest program

Here is a complete Dart program:

DART
void main() {
  print('Hello, world!');
}

Take it apart piece by piece:

  • void is the return type. main does not give anything back.
  • main is the entry point. Dart calls it when the program starts.
  • () is the parameter list, empty here.
  • { ... } is the body, the statements to run.
  • print('Hello, world!'); calls the built-in print function with a string. It writes the text and a newline to the console.
  • The ; ends a statement. Dart requires semicolons, unlike Python or Go.

Save this as hello.dart and run dart run hello.dart. The console shows:

TEXT
Hello, world!
TypeScript The same shape in TypeScript (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The one visible difference is that in Dart you do not call main() yourself. The runtime does it.

main can take arguments

When you run a program from a terminal you can pass it words, such as dart run hello.dart Ada Grace. To receive them, declare a parameter of type List<String>:

DART
void main(List<String> arguments) {
  print('You passed ${arguments.length} arguments.');
  print(arguments);
}

With the command above, this prints You passed 2 arguments. and then [Ada, Grace]. Note how Dart prints a list: square brackets, items separated by a comma and a space, and no quotes around strings. Both forms of main are valid. Use the one with arguments only when you need them.

Printing and string interpolation

print accepts any object. It converts it to a string (by calling toString()) and prints it. That means you can print numbers, booleans and lists without converting them yourself:

DART
void main() {
  print('Dart');
  print(42);
  print(3.5);
  print(true);
  print([1, 2, 3]);
  print(null);
}
TEXT
Dart
42
3.5
true
[1, 2, 3]
null

Joining text and values is done with string interpolation. Put a $ before a variable name to insert its value, or ${...} to insert any expression:

DART
void main() {
  var name = 'Ada';
  var age = 36;
  print('Hello, $name!');
  print('Next year you will be ${age + 1}.');
  print('Your name has ${name.length} letters.');
}
TEXT
Hello, Ada!
Next year you will be 37.
Your name has 3 letters.

The short $name form works for a plain variable name. As soon as you need a property, a method call or any arithmetic, use the braces: ${name.length}. A common slip is writing $name.length, which inserts the name and then the literal text .length.

Prefer interpolation over joining strings with +. It is shorter, and it works with any type because every object can be turned into a string.

TypeScript Interpolation, written with template literals (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

To print a literal dollar sign, escape it with a backslash: print('Price: \$5');. You can also use a raw string, r'Price: $5', which turns off escapes and interpolation.

Comments

Dart has three kinds of comments:

DART
// A single-line comment runs to the end of the line.

/* A block comment
   can span several lines. */

/// A documentation comment. Tools turn these into API docs.
/// It describes the declaration that follows.
void greet(String name) {
  print('Hello, $name!'); // A comment can also follow code.
}

Use // for notes to yourself. Use /// to document functions, classes and fields: editors show these comments in hover tips, and dart doc turns them into a website. Documentation comments can contain Markdown, including backticked code and [brackets] that link to other names. Block comments are rare in practice.

The older Javadoc-style block /** ... */ is also a documentation comment, but the Dart style guide prefers /// lines. Block comments can be nested, so /* outer /* inner */ still a comment */ is valid, which makes it easy to comment out code that already contains block comments.

Ending a program early

A program ends when main returns and no asynchronous work is pending. To stop right away, call exit(code) from dart:io: the code 0 means success and any other value signals failure to the shell, so scripts can react. exit skips any remaining code, including finally blocks, so use it only in command-line programs (never in Flutter apps):

DART
import 'dart:io';

void main(List<String> args) {
  if (args.isEmpty) {
    stderr.writeln('Usage: tool <name>');
    exit(64);                    // 64 is the conventional "usage error" code
  }
  print('Hello, ${args.first}!');
}

How a file is organized

A Dart file is a list of top-level declarations. Unlike some languages, Dart lets you put functions and variables at the top level, outside any class. A typical file follows this order:

flowchart TD
    A["1. imports<br/>import 'dart:math';"] --> B["2. top-level constants and variables"]
    B --> C["3. functions and classes"]
    C --> D["4. main() - often at the top or bottom"]

Imports come first, then declarations. The position of main() does not matter, because Dart reads the whole file before running it.

Here is a slightly bigger program that uses all of those parts:

DART
import 'dart:math';

const greeting = 'Dice game';

int rollDie(Random random) {
  return random.nextInt(6) + 1;
}

void main() {
  print(greeting);
  var random = Random();
  var roll = rollDie(random);
  print('You rolled a $roll.');
}

The import 'dart:math'; line makes Random available. Names that start with dart: are libraries that ship with the SDK. The function rollDie has a return type (int) and a typed parameter, and it can be called before or after the place where it is written, because top-level names are visible throughout the file.

Notice what is missing: there is no new keyword before Random(). Since Dart 2 you simply call the constructor. Notice also the indentation: two spaces, which is what dart format produces.

TypeScript A tiny program with a helper function (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Errors you will see early

Two small mistakes catch nearly everyone in the first week:

  1. A missing semicolon. The analyzer reports "Expected to find ';'" and points at the end of the line before. The fix is to add it.
  2. Single versus double quotes. 'text' and "text" are both strings and behave the same. Pick one style. The Dart style guide prefers single quotes unless the text contains one.

A third surprise comes from other languages: statements only run inside functions. You cannot write print('hi'); at the top level of a file; it has to be inside main or another function.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the Dart runtime do when you run a program?

    main is the entry point. The position of main in the file does not matter.
  2. 2. With var name = 'Ada';, which line prints the number of letters in the name?

    Use ${...} for anything beyond a plain variable name. $name.length would print the name followed by the text .length.
  3. 3. Which comment style is used by documentation tools?

    Triple-slash comments are documentation comments. Editors show them on hover and dart doc builds API pages from them.
  4. 4. How do you print a literal dollar sign in a normal string?

    A backslash escapes the dollar sign, so '\$5' prints $5. A raw string such as r'$5' also works.

Summary

  • A Dart program starts by calling main(); use main(List<String> arguments) to receive command-line arguments.
  • print converts any object to text and writes it with a newline.
  • Interpolation inserts values into strings: $name for a variable, ${expression} for anything else.
  • Comments are //, /* */ and the documentation form ///.
  • Files list imports first, then top-level constants, functions and classes; statements only run inside functions.

Next, learn how to store values in Variables, var, final and const.