Your First Dart Program
Prerequisites: Installing Dart
Every Dart program starts in a function called main. Create a file
called hello.dart:
void main() {
print('Hello, world!');
}
Run it from the folder that contains it:
dart run hello.dart
Expected output
Hello, world!
Line by line:
void main()declares the main function — where the program starts.voidmeans it doesn't return a value.- The curly braces
{ }hold the function's code. print(...)writes a value to the screen, followed by a new line.'Hello, world!'is a string — text in quotes. Dart accepts single or double quotes; single quotes are the usual style.- Each statement ends with a semicolon
;.
A slightly longer program runs line by line, top to bottom:
void main() {
print('Hello, world!');
print('I am learning Dart.');
print(2 + 3);
}
Hello, world!
I am learning Dart.
5
Common mistakes
- Forgetting a semicolon. Dart reports
Error: Expected ';' after this.and points at the spot. - Writing
Printwith a capital P. Dart is case-sensitive.
Practice
Write a program that prints your name on one line and your favorite food on the next.
Show solution
void main() {
print('Ada');
print('Pizza');
}