Sub topic 1
Anatomy of a Dart program
Prerequisites
This chapter assumes you have:
- Programmed in at least one language, so you know what functions, variables, and modules are.
- A terminal and a code editor, with the Dart SDK installed. Run
dart --versionto check. Installing Flutter also installs Dart. - Some familiarity with classes and objects. This chapter only mentions them. Later chapters cover them in full.
By the end you should be able to read a small Dart file and name each part. You should also be able to create a console project, run it, pass it arguments, and explain why a file does or does not run.
The smallest program
A Dart program starts at a top-level function named main. The tool that runs your code looks for this function and calls it.
void main() {
print('Hello, Dart!');
}Each piece has a job:
voidis the return type. It meansmainreturns no value.mainis the entry point name. It must be spelled exactly this way, in lowercase.()is the parameter list. It is empty here.printis a function from the core library. It writes a line to standard output. Dart importsdart:coreautomatically, so you do not write an import for it.- Statements end with
;. Blocks use{ }. Forgetting a semicolon is a compile error, not a style issue.
Save this as hello.dart and run dart run hello.dart. You can also run dart hello.dart.
Statements, expressions, and comments
Dart separates statements from expressions. An expression produces a value, such as 1 + 2 or name.length. A statement does something, such as declaring a variable or running a loop. A statement can contain expressions. Most expressions cannot stand alone as code without a trailing ;.
Comments come in three forms:
// A single-line comment.
/* A block comment
that spans lines. */
/// A documentation comment. Tools such as `dart doc` and your editor read these.
void main() {
print('Comments do not run.');
}Use /// above public declarations. Editors show these comments in hover tooltips.
Variables inside main
Most programs declare values near the top of main. The next chapter covers var, final, and const in detail. For now, read this example for its structure.
void main() {
final name = 'Dart';
var version = 3;
const pi = 3.14159;
version = version + 1;
print('Hello, $name $version ${pi * 2}');
}Dart infers each variable's type from its initial value. $name and ${pi * 2} are string interpolation, which inserts a value into a string. Use $name for a bare identifier. Use ${...} for any other expression.
Accepting command-line arguments
main can take one optional parameter of type List<String>. Dart fills it with the arguments after the script name.
import 'dart:io';
void main(List<String> args) {
if (args.isEmpty) {
stderr.writeln('Usage: dart run greet.dart <name>');
exitCode = 64;
return;
}
print('Hello, ${args.first}!');
}Running dart run greet.dart Ada prints Hello, Ada!. Running it with no arguments writes the usage text to standard error. It also sets the process exit code to 64, a conventional "usage error" value.
Three details matter here:
import 'dart:io';loads the I/O library. It providesstderrandexitCode. It is not available in browser builds.exitCodeis a top-level property fromdart:io. Setting it letsmainfinish normally and still report failure to the shell. Callingexit(64)instead stops the process immediately.- A bare
return;in avoidfunction ends it early.
Top-level declarations
A Dart file is a library. A library can hold more than main. Functions, variables, constants, classes, enums, and extensions can all sit at the top level. Dart has no required wrapper class, unlike Java or C#.
import 'dart:math' as math;
const appName = 'Demo';
int _counter = 0;
int nextId() => ++_counter;
double circleArea(double r) => math.pi * r * r;
void main() {
print('$appName: ${nextId()}, ${nextId()}');
print(circleArea(2).toStringAsFixed(2));
}This prints Demo: 1, 2 and then 12.57. Notice these points:
import 'dart:math' as math;gives the library a prefix. You writemath.piinstead ofpi. Prefixes avoid name clashes.=>is shorthand for a function whose body is a single expression that it returns.- A name that starts with an underscore, like
_counter, is private to its library. Dart has noprivatekeyword. Privacy applies per library, which usually means per file. It does not apply per class.
Top-level variables are lazy
Top-level variables are not initialized when the program starts. Dart initializes each one the first time you read it. This example shows the order:
String _stamp() {
print('initializing');
return 'ready';
}
final startedAt = _stamp();
void main() {
print('main started');
print(startedAt);
print(startedAt);
}The output is main started, then initializing, then ready twice. The initializer runs once, on first access. This avoids start-up work for values you never use. It also means an initializer with side effects, like the print above, may run later than you expect.
Imports and where code lives
Dart code reaches other code through import directives, which sit at the top of the file before any declarations. There are three common forms.
| Form | Example | Use it for |
|---|---|---|
| SDK library | `import 'dart:async';` | Libraries that ship with Dart |
| Package | `import 'package:path/path.dart';` | Code from `pubspec.yaml` dependencies or your own package's `lib/` |
| Relative path | `import 'src/helpers.dart';` | Files in the same package |
Two modifiers you will meet early are as for prefixes and show or hide for limiting what an import brings in:
import 'dart:math' show Random;
import 'dart:convert' as convert;Project layout
A single file is enough to learn on. Real programs live in a package, which is a directory with a pubspec.yaml file. Create one with dart create:
dart create -t console my_app
cd my_app
dart runThe generated layout looks like this:
| Path | Purpose |
|---|---|
| `pubspec.yaml` | Package name, SDK constraint, and dependencies |
| `bin/my_app.dart` | Executable entry point that contains `main` |
| `lib/` | Reusable code that other packages can import |
| `test/` | Tests |
| `analysis_options.yaml` | Analyzer and lint settings |
The convention is to keep main small. It reads input and calls into code under lib/. Flutter apps follow the same pattern. The main in lib/main.dart calls runApp.
How a Dart program runs
The same source can run in different ways. This affects how you build and debug.
dart runuses the VM with just-in-time (JIT) compilation. It starts quickly and supports debugging. In Flutter, the same VM mode powers hot reload.dart compile exeproduces a self-contained native executable through ahead-of-time (AOT) compilation.dart compile jstargets browsers.
Before any of these, the analyzer checks the code. dart analyze runs this check alone. dart format . applies the standard layout. Run both often.
Asynchronous main
When main uses await, declare it async and return a Future<void>:
Future<void> main() async {
await Future.delayed(const Duration(milliseconds: 100));
print('finished waiting');
}Dart waits for the returned future before the program exits. A later chapter covers futures properly. Here, just remember the signature.
Common errors
- "Missing main" or nothing happens. The file you ran has no top-level
main, or you ran a file underlib/that only defines helpers. Run the file underbin/. - Misspelled
Mainormain2. Dart treats names as case-sensitive. Onlymainis the entry point. Undefined name 'stderr'. You forgotimport 'dart:io';.- A private name is not found from another file. A leading underscore hides it from every other library.
- Expected
;. A missing semicolon fails compilation. The error often points at the next line. - Wrong
mainsignature.mainaccepts either zero parameters or a singleList<String>. Other parameter lists are rejected.
Exercises
Exercise
A file contains final id = _makeId(); at the top level, and _makeId prints "making id". The main function prints "start" and then reads id once. In what order do the two lines appear, and why?
Show answer
"start" appears first, then "making id". Top-level variables are lazy. Dart runs the initializer on the first read, which happens after main has already printed "start".
Exercise
Write a program that takes one command-line argument, prints its length, and sets exit code 64 with a message on standard error when no argument is given.
Show answer
import 'dart:io'; void main(List<String> args) { if (args.isEmpty) { stderr.writeln('Usage: dart run len.dart <text>'); exitCode = 64; return; } print(args.first.length); }