Sub topic 1
Anatomy of a Dart program
Prerequisites
Assume you can read basic code, use a terminal and code editor, and understand that classes create objects. This chapter focuses on how a Dart file is organized and how execution begins.
A Dart program is a text file containing declarations and statements. A declaration introduces something, such as a function or variable. A statement performs an action. Dart usually runs a program by calling a top-level function named main.
The entry point
The simplest executable Dart program is:
void main() {
print('Hello, Dart');
}Read this from left to right:
voidis the function's return type. It means the function does not return a value.mainis the function name recognized as the program entry point.()contains the function's parameters. Thismainfunction has none.{and}contain the function body.printwrites text to the terminal.- A semicolon ends the statement.
When you run the file, Dart starts at main, executes its statements in order, and then exits.
A function can also receive command-line arguments through List<String> args:
void main(List<String> args) {
print('Argument count: ${args.length}');
}The ${...} syntax evaluates an expression inside a string. The expression here reads the length property of the argument list.
Declarations and execution
Dart files can contain top-level declarations before or after main. A common structure puts reusable functions above main and keeps main responsible for starting the program.
String makeGreeting(String name) {
return 'Hello, $name!';
}
void main() {
final greeting = makeGreeting('Ada');
print(greeting);
}makeGreeting is a top-level function. It accepts a String named name and returns a String. The return statement sends a value back to the caller.
final greeting declares a local variable whose value cannot be replaced after initialization. The function call happens before print, so the execution order is:
- Enter
main. - Call
makeGreeting. - Return the greeting.
- Store it in
greeting. - Print it.
Dart permits declarations to appear in either order, but keeping the entry point easy to find improves readability.
How the pieces connect
Comments document intent and do not execute:
void main() {
// This comment explains the next statement.
print('Ready');
}Use // for a single-line comment. Dart also supports block comments with /* and */, but comments should explain decisions rather than repeat obvious code.
Running a program
Save the first example as hello.dart, then run it from a terminal:
dart run hello.dartThe Dart SDK reads the file, checks it, starts main, and reports output or errors. A syntax error prevents execution. A runtime error occurs after execution has started.
Exercise
Which function does Dart call first in a normal executable Dart program, and what does void mean in its declaration?
Show answer
Dart calls main first. void means that the function does not return a value.