What Is Dart and How Do You Run It?
Dart is a programming language made by Google. It is the language behind Flutter, a popular tool for building phone apps. Dart looks friendly and works on Windows, Mac, and Linux.
To run Dart, you install the Dart SDK (the free toolkit that reads and runs Dart code). Then you use the dart command in your terminal:
dart run hello.dartYour First Dart Program
Every Dart program starts at a function named main. A function is a named block of code. Here is a complete program:
void main() {
print('Hello, Dart!');
}Save it as hello.dart and run dart run hello.dart. You will see Hello, Dart! printed.
Variables, Types, and Inference
A variable is a named box that holds a value. Each value has a type, like String (text) or int (whole numbers). You can write the type yourself, or let Dart guess it — that guess is called inference:
String name = 'Ada'; // you say the type
var year = 1815; // Dart infers: it's an int
final greeting = 'Hi, $name!'; // final means it can't change
print(greeting); // Hi, Ada!The $name inside quotes is string interpolation: it drops a variable's value into text.
Null Safety: Living Without Surprises
Sometimes a variable should hold "nothing" — Dart calls nothing null. By default, Dart does not allow null. You must mark a variable with ? to say it may be empty:
String? maybeName; // starts as null
print(maybeName ?? 'guest'); // prints: guest
maybeName ??= 'Ada'; // set it only if it's still null
print(maybeName!.length); // ! promises: it's not null nowThis catches "empty value" mistakes before your program even runs.
Control Flow: Decisions and Loops
Programs need to make choices and repeat steps. Use if for choices and for for repeats:
for (var i = 1; i <= 3; i++) {
if (i == 2) {
print('middle!');
} else {
print('number $i');
}
}caption: A loop runs three times, printing a different message when i equals 2. alt: Flowchart showing a loop that checks whether i equals 2, prints a message either way, adds 1 to i, and stops after three passes.
Exercise
What does String? mean that plain String does not?
Show answer
String? allows the value to be null (nothing), while plain String must always hold actual text.
Spotted a mistake, or code that does not work?