Dart Syntax – The Basics
Syntax is the set of rules that defines how a Dart program is written. Just like grammar in human language, syntax ensures that your code is structured correctly so the Dart compiler can understand and execute it. This guide covers the fundamental syntax elements every Dart developer must know.
- Statements and Semicolons
In Dart, each instruction is called a statement. Statements must end with a semicolon (;). Forgetting a semicolon is a common syntax error.
- Comments
Comments are ignored by the compiler and are used to explain code. Dart supports three types of comments:
- Single‑line comments start with
//and continue to the end of the line.
- Single‑line comments start with
- Multi‑line comments are enclosed between
/*and*/.
- Multi‑line comments are enclosed between
- Documentation comments start with
///or/**and are used by tools likedart doc.
- Documentation comments start with
- The
main() Function
main() FunctionEvery Dart program must have a main() function. It serves as the entry point – the first code that runs when you execute the program. The main() function can be written with or without a return type (void means it returns nothing).
- Printing to the Console
The print() function outputs text to the console. It's useful for debugging and displaying results.
- Case Sensitivity
Dart is case‑sensitive. That means myVariable, MyVariable, and MYVARIABLE are all different names. Always use consistent casing to avoid errors.
- Code Blocks and Indentation
Code blocks are enclosed in curly braces {}. They group multiple statements together, for example in functions, loops, or conditionals. Dart uses braces, not indentation, to define blocks, but consistent indentation is strongly recommended for readability.
- Keywords
Dart has a set of reserved words (keywords) that have special meaning. You cannot use them as identifiers (variable names, function names, etc.). Examples: if, else, for, while, class, void, int, String, true, false, null, var, final, const.
- Identifiers
Identifiers are names given to variables, functions, classes, etc. Rules:
- Can contain letters, digits, underscores (
_), and dollar signs ($).
- Can contain letters, digits, underscores (
- Cannot start with a digit.
- Cannot be a keyword.
- By convention, variable and function names use
camelCase(e.g.,myVariable), and class names usePascalCase(e.g.,MyClass).
- By convention, variable and function names use
Complete Example
Key Takeaways
- Every statement ends with a semicolon.
- Use comments to document your code.
- Every program needs a
main()function.
- Every program needs a
- Dart is case‑sensitive.
- Code blocks are enclosed in
{}.
- Code blocks are enclosed in
- Follow naming conventions for readability.