Sub topic 1
Anatomy of a Dart Program
This chapter covers the parts of a Dart file you will use in almost every program: the entry point, variables, strings, null safety, and control flow.
Prerequisites
You should know one programming language and be comfortable with a terminal. You should also understand basic object-oriented ideas such as classes. You need the Dart SDK installed so you can run dart run file.dart.
The entry point
Every Dart program starts at a top-level function named main. Dart runs the code inside main first, and it runs the statements in order from top to bottom.
void main() {
print('Program started');
}Variables, final, const, and built-in types
Dart is statically typed, but it infers types from values. Use var for a variable that can change, final for a variable you assign once at runtime, and const for a value fixed at compile time.
void main() {
final language = 'Dart';
var version = 3;
const pi = 3.14159;
version = version + 1;
print('$language $version ${pi * 2}');
}The common built-in types are int, double, bool, String, and List.
Strings and interpolation
Interpolation inserts a value into a string. Use $name for a simple variable and ${expression} for any expression.
Sound null safety
In Dart, a type without ? cannot hold null. Add ? to allow null. Use ?. to call a member only when the value is not null, ?? to supply a fallback, and ??= to assign only when the variable is null.
String? findUser(int id) => id == 1 ? 'Ada' : null;
void main() {
final user = findUser(2);
print(user?.toUpperCase() ?? 'unknown');
String? nickname;
nickname ??= 'guest';
print(nickname);
}Use ! only when you are certain a value is not null. If you are wrong, the program throws at runtime.
Control flow: conditions and loops
Dart uses if, else, for, and while in the same way as C-style languages.
void main() {
for (var i = 1; i <= 5; i++) {
if (i.isEven) {
continue;
}
print('odd: $i');
}
}Exercise
Given String? name = null;, what does print(name?.length ?? 0); print?
Show answer
It prints 0. The ?. operator returns null because name is null, and ?? replaces that null with 0.
Exercise
Why does const x = DateTime.now(); fail to compile?
Show answer
DateTime.now() returns a value known only at runtime, but const requires a value known at compile time. Use final instead.