Learn/Dart/1. Hello, output
Lesson 1 of 8
Sign in

Dart, lesson 1

Hello, output

Every Dart program starts in a function called main. When you run the file, Dart looks for main, runs the statements inside its curly braces one after another, and stops when it reaches the closing brace.

void means main does not hand any value back when it finishes. print() writes a value to the screen and then moves to a new line. Every statement ends with a semicolon ;. Forgetting one is the most common first error, and the compiler will point at the line.

Text in quotes is a string. Dart accepts single quotes ('hi') and double quotes ("hi"). Most Dart code uses single quotes, and so do these lessons.

Writing without a new line

always adds a line break. When you want to build one line from several pieces, use from the library. It writes exactly what you give it and nothing more:

2 exercises to try what you just read.

Exercise 1

Your first program

Press Ctrl Enter or Check to test your code.

Exercise 2

A countdown banner

Press Ctrl Enter or Check to test your code.

print()
stdout.write()
dart:io

The import line goes at the very top of the file. It makes the input/output tools in dart:io (such as stdout and, later, stdin) available to your code.

Putting values inside strings

You can drop a value into a string with $. For anything more than a plain name, wrap it in ${...}:

This is called string interpolation, and you will use it constantly.

Comments

Comments are notes for people. Dart ignores them.

How a program runs

Dart compiles your file before running it. If something is wrong, such as a missing semicolon or a misspelled name, you get a compile error and nothing runs at all. Read the message: it names the file, the line and column, and what Dart expected. Once the program compiles, statements in main run strictly in order, top to bottom.

Further reading

  • Introduction to Dart
  • Comments
  • dart:io library overview

Write a program that prints exactly these two lines:

The program reads no input.

Print a launch countdown on one line using stdout.write() for each of 3... , 2... and 1... , then finish the line with print('Liftoff!'). On the next line, use string interpolation to print Crew: 4 where the 4 comes from the expression 2 + 2 inside ${...}.

Expected output:

void main() {
  print('Hello, World!');
  print('Dart starts here, in main().');
}
import 'dart:io';

void main() {
  stdout.write('Loading');
  stdout.write('...');
  print('done'); // Loading...done
}
void main() {
  print('2 + 3 = ${2 + 3}'); // 2 + 3 = 5
}
// A single-line comment runs to the end of the line.

/* A multi-line comment
   can span several lines. */

/// A doc comment (three slashes) describes the thing below it.
void main() {
  print('Only this line runs'); // a comment can follow code too
}
Hello, World!
I am learning Dart.
3... 2... 1... Liftoff!
Crew: 4