Every Dart program starts in a function called main. print writes a line to the console, which is handy while you learn.
void main() {
print('Hello, Dart!');
}Variables and types
varlets Dart work out the type:var city = 'Phnom Penh';is aString.finalis set once and never changes. Use it for most values.constis a value that is known before the app runs, likeconst pi = 3.14;.- Common types:
int(whole numbers),double(decimals),String(text) andbool(true or false).
final String name = 'Dara';
int score = 8;
score = score + 1; // allowed: score is not final
const bool isBeginner = true;Putting values into text
Write $name inside a string to insert a variable, or ${...} for an expression, like ${score * 10}. This is called string interpolation.
Functions
A function lists its return type, its name and its parameters. When the body is a single expression you can use the short arrow form =>.
int add(int a, int b) {
return a + b;
}
String greet(String name) => 'Hello, $name!';Null safety
A normal variable can never be null. Add ? to the type when a value may be missing, and use ?? to give a fallback.
Code examples
Expected output
Sievchhing finished 4 lessons. Keep going, Sievchhing!
lessonsDone++ adds one, so it becomes 4. greet uses the arrow form to return a string in one line.
Common mistakes
Common mistake: Joining a number to text with +
'Age: ' + 20 is an error in Dart. Use interpolation instead: 'Age: $age'.
Common mistake: Giving null to a non-nullable variable
String name = null; does not compile. Write String? name; if the value can really be missing.
Check your understanding
3 quick questions about this lesson.