Explain it simply
Syntax, simply
Syntax is the grammar of a language. Every Dart program is built from a small set of pieces: functions, statements, expressions and comments. A statement is a complete instruction such as print('Hi'); and it ends with a semicolon. An expression is a piece of code that produces a value, such as 10 + 5, and you can place expressions inside statements.
Comments are notes for people, and Dart skips them. Once you can tell these pieces apart, Dart's error messages start to make sense, and the code you write becomes easy for other people to read.
Problem → Why → Solution
The problem: one missing brace or semicolon and nothing runs
The program below has two mistakes: the second print lacks its semicolon, and main() lacks its closing }. Dart does not even run the first print, because it reads the whole file first and prints only errors when it finds any. The first error is hello.dart:1:13: Error: Can't find '}' to match '{'. and the second is hello.dart:3:30: Error: Expected ';' after this.
A common beginner reaction is to fix only the first error and expect every message to vanish, or to stare at the reported line without seeing that the other half of a brace is somewhere else. One mistake can cause further errors, so read the list from the top, in order.
void main() {
print('Hello, Dart!');
print('Syntax is a grammar')
print('Done');Why the grammar is this strict
Braces tell Dart exactly where a block starts and ends, and semicolons tell it where a statement finishes. Without them the compiler would have to guess what you meant, and a wrong guess could silently become a wrong program. Stopping and telling you is the safer choice.
Core concept: statements, expressions and blocks
Every Dart file is built from a few kinds of pieces, and learning to tell them apart makes error messages readable. A statement is a complete instruction such as print('Hi'); and it ends with a semicolon. An expression is code that produces a value, such as 10 + 5 or 'Hi'.length. Expressions are the ingredients and statements are the finished dishes. A block, written with curly braces, groups statements together, and the body of main() is a block.
1. Start at main()
Dart looks for the top-level function main and runs its block from the first statement downwards, in order.
2. Close statements with a semicolon
The semicolon tells Dart where one instruction stops. It is not needed after the closing brace } of a block.
3. Let expressions produce values
In print(10 + 5); the expression 10 + 5 is worked out first and its result is handed to print. Expressions also fit inside ${ } in a string.
4. Leave notes in comments
Dart skips comments completely, so they never change the program's output. Use them to say why the code is written the way it is.
| Kind of comment | Written as | Used for |
|---|---|---|
| Line comment | // text | A short note on one line |
| Block comment | /* text */ | Longer notes over several lines, or switching code off for a moment (they can be nested) |
| Doc comment | /// text | Documenting a function, class or variable; editors show it on hover and dart doc turns it into web docs |
Text goes inside quotes. Single and double quotes behave the same, so choose whichever saves you a backslash: 'It\'s easy' needs one, but "It's easy" does not. Inside a string, $name inserts a variable and ${expression} inserts any expression, so '${10 + 5}' becomes 15. A backslash starts an escape such as \n for a new line, and \$ prints a literal dollar sign.
Dart is case-sensitive: Main and main are different names, and Print is not print. By convention variable and function names use lowerCamelCase, types use UpperCamelCase and file names use lowercase_with_underscores. dart format also fixes the layout, using two spaces of indentation.
- Dart finds main() and enters its block
- Statements run in order, each ends in ;
- Expressions inside are evaluated first
- print() writes the result as text
Braces and quotes come in opening and closing pairs; when one half is missing, Dart stops and reports it in the very first error.
General pattern: statements inside main
void main() {
// line comment
print(expression);
print('text $variable and ${expression}');
/* block
comment */
}Inside the { } of main() the statements are written from top to bottom. Each print(...) is a statement that ends with a semicolon, and what sits inside the parentheses is an expression. Both kinds of comment can go anywhere.
Hello World with every syntax piece
This program uses all three comment kinds, a numeric expression, both quote styles and string interpolation across four print statements. Before running it, write down what each print prints, paying special attention to the two lines that contain 10 + 5.
/// The entry point: every Dart program starts here.
void main() {
// A single-line comment explains one idea.
print('Dart is clear and practical.');
/* A block comment
can span several lines. */
print(10 + 5); // the expression 10 + 5 is evaluated, then printed
print("It's easy"); // double quotes avoid escaping the apostrophe
print('Sum: ${10 + 5}'); // ${...} runs any expression inside a string
}Code breakdown
- A doc comment
/// The entry point: every Dart program starts here./// is a doc comment that describes the declaration below it, main(). Editors show this text when you hover over main. It does not change how the program behaves.
- The block
void main() {The { opens main()'s block and the final } closes it. main() runs only the statements between the two.
- A statement with a string
print('Dart is clear and practical.');This statement passes the text in single quotes to print as its argument, and the final semicolon closes it. It produces the first line of output.
- A block comment
/* A block commentStarting with /* and ending with */, it covers two lines, and Dart does not read the text in between at all.
- An expression inside print
print(10 + 5);10 + 5 is an expression: it is worked out first and 15 is handed to print, so the output is 15 rather than the text 10 + 5. The trailing // comment is only a note.
- Double quotes
print("It's easy");The text contains an apostrophe, so it is opened with double quotes. Opened with single quotes, Dart would think the text ended at the apostrophe.
- Interpolating an expression
print('Sum: ${10 + 5}');The 10 + 5 inside ${ } is worked out and its result placed into the text, so this prints Sum: 15. Without the ${ } the expression would appear as plain text.
Dart is clear and practical.
15
It's easy
Sum: 15- dart run reads the file
- Braces, quotes and semicolons are checked
- Names and types are checked
- main() runs
The syntax is valid
Every print statement runs, top to bottom
The syntax is broken
Nothing runs, not even the lines above the mistake; you see only error messages
Strings in more detail
The snippet below shows how to write a string that contains a new line, a tab, a dollar sign or Myanmar text. \n and \t are escapes, while a raw string that starts with r keeps a backslash as ordinary text. A string opened with three quotes can span several lines, and Dart ignores a line break placed right after the opening quotes. Source files are UTF-8, so Myanmar text can go straight inside the quotes.
void main() {
print('Line one\nLine two');
print(r'Raw strings keep \n as two characters');
print('''
A multi-line string
keeps its line breaks.''');
print('Price: \$5');
print('မင်္ဂလာပါ, Dart!');
print('Tab\tseparated');
}Reading the most common syntax errors
| Message | What it means | Fix |
|---|---|---|
| Expected ';' after this. | A statement lacks its semicolon; the arrow points at the end of the line | Add ; at the end of that line |
| Can't find '}' to match '{'. | A block was opened and never closed; the error points at the opening { | Add the closing brace and check the layout with dart format |
| Expected a declaration, but got '}'. | There is one closing brace too many | Remove the extra } |
| String starting with ' must end with '. | A quote was opened and not closed, for example an apostrophe inside single quotes | Use double quotes or escape the apostrophe as \' |
| Method not found: 'Print'. | Dart is case-sensitive, so Print does not exist | Write print in lowercase |
In real projects
Syntax habits in real projects
Teams run dart format every time an editor saves, or in CI. With dart format --set-exit-if-changed, a build can fail when a file is not formatted. Code review then stops being about the placement of spaces and braces and stays focused on logic.
Doc comments do real work too. When every public function in a library has a /// description, dart doc can generate web documentation, and a package's API pages on pub.dev are built from those comments. In the same spirit, a widely used lint rule called avoid_print warns about print() in app code, because real apps are better off with logging they can control. In this course's examples, print() is still the best way to see output.
Common mistakes
Common syntax mistakes
1. Reading the error list from the bottom
The first error is usually the real cause, and the ones after it are often consequences. Fix the first one, run again, and only then deal with whatever is left.
2. An apostrophe inside a single-quoted string
print('It's easy'); produces about four errors, the first being String starting with ' must end with '. Dart reads the apostrophe as a closing quote. Write "It's easy" with double quotes, or escape it as 'It\'s easy'. Writing 'It''s easy' in SQL style gives no error and prints Its easy, because Dart joins two adjacent string literals.
3. Forgetting the braces in interpolation
'$word.length' does not call .length: it inserts $word and then writes .length as plain text, so with word equal to 'Dart' it prints Dart.length. After a $ only a plain name is taken, so in cases like this write '${word.length}'.
4. Getting the capital letters wrong
Print('x'); gives Method not found: 'Print'. Dart is case-sensitive, so keywords and built-in functions must be written in lowercase. Using the editor's autocomplete makes this slip rare.
Best practices
Best practices
- Run dart format whenever you save a file, and never align indentation by hand.
- Write comments that explain why the code does something, not what it does; do not restate what is easy to read.
- Give every public function a /// doc comment, with a one-line summary as its first sentence.
- Keep one quote style across the project, and switch to double quotes only when the text contains an apostrophe.
Mini challenge
Mini challenge: a tea-shop receipt
Write a program that prints a receipt for a tea shop: 2 teas at 1500 kyat each and 1 coffee at 2500 kyat. Calculate the amounts with expressions and use all three kinds of comment.
- Add a /// doc comment above main(), and one // comment and one /* */ comment inside it
- Print the tea, coffee and total amounts, calculated by expressions inside ${ }
- Print Chef's special: free biscuit from a double-quoted string that contains an apostrophe
- Finish with a multi-line string written with ''' that prints Thank you! and Come again.
// TODO: add a /// doc comment on the line above main()
void main() {
// TODO: a // comment saying the prices are in kyat
// TODO: print the tea amount (2 x 1500) with an expression inside the string
// TODO: print the coffee amount (1 x 2500) the same way
// TODO: a /* ... */ comment, then print the total with one combined expression
// TODO: print the Chef's special line using double quotes
// TODO: print a two-line thank-you message with a ''' string
}Expected: The program prints these six lines: Tea: 3000 MMK Coffee: 2500 MMK Total: 5500 MMK Chef's special: free biscuit Thank you! Come again.
Show hint
Start with 'Tea: ${2 * 1500} MMK'. For the total, write one combined expression such as ${2 * 1500 + 1 * 2500}. The multi-line string opens with print('''Thank you! and closes on the next line after Come again.''').
Show solution
/// Prints a small receipt for a tea shop.
void main() {
// Prices are in kyat.
print('Tea: ${2 * 1500} MMK');
print('Coffee: ${1 * 2500} MMK');
/* The total repeats the two
calculations above. */
print('Total: ${2 * 1500 + 1 * 2500} MMK');
print("Chef's special: free biscuit");
print('''Thank you!
Come again.''');
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A statement ends with a semicolon, an expression produces a value, and a block is grouped with { }
- Three comment kinds: // for a line, /* */ for a block and /// for documentation
- Strings use single or double quotes, and $name and ${expression} insert values
- A syntax error stops everything from running, so read the error list from the top, in order
Dart 3.13 changelog — Dart