Comments are notes written in source code that the compiler ignores. They help you and other developers understand what the code does. Good comments explain why code exists, not just what it does.
Single-Line Comments
Use // to write a single-line comment. Everything after // on that line is ignored.
void main() {
// This is a single-line comment
print('Hello'); // This comment is at the end of a line
// TODO: Add input validation later
int score = 95;
}
Multi-Line Comments
Use /* ... */ for comments that span multiple lines.
void main() {
/*
This is a multi-line comment.
It can span as many lines as needed.
Useful for temporarily disabling blocks of code.
*/
print('Multi-line comments work!');
}
Use /// for documentation comments. These are read by the dart doc tool to generate API documentation.
/// Calculates the area of a rectangle.
///
/// [width] is the width of the rectangle.
/// [height] is the height of the rectangle.
/// Returns the area as a double.
double calculateArea(double width, double height) {
return width * height;
}
Example
void main() {
// Step 1: Define the items and prices
double price = 49.99;
int quantity = 3;
/*
Step 2: Calculate total
Apply 10% discount for quantities > 2
*/
double total = price * quantity;
if (quantity > 2) {
total = total * 0.9; // 10% discount
}
print('Total: \$$${total.toStringAsFixed(2)}');
}
Best Practices
- Write comments that explain why, not what (the code shows what).
- Keep comments up to date when you change the code.
- Use
/// doc comments for public APIs and functions.
- Use
// TODO: to mark incomplete features.
- Avoid commenting obvious code like
// increment i by 1 before i++.
🧠 Quiz
1. Which symbol starts a single-line comment in Dart?
2. Which comment style is used for API documentation in Dart?
- A) /* */
- B) //!
- C) /// ✅
- D) /** */
Summary
Dart supports three types of comments: single-line (//), multi-line (/* */), and documentation (///). Comments are ignored by the compiler. Use them to explain your code and generate documentation with dart doc.