On this page11 sections
Lecture 005 — Comments
| Category | 2 — Getting Started |
| Lecture | 005 of 057 |
| Estimated video length | 8 min |
| Target | Dart 3.12 |
| Level | Beginner |
Comments are notes in your code that Dart ignores. We learn the three kinds and when each one is useful.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lecture 004: you can write and run main with print.
Learning Objectives
- Write single-line, multi-line and documentation comments
- Use comments to switch code off while testing
- Write comments that actually help
1. Single-Line Comments
Everything after // to the end of the line is ignored.
// Prints a welcome message
print('Welcome!'); // a comment can also follow code2. Multi-Line Comments
Everything between /* and */ is ignored, however many lines.
/*
This program prints the class schedule.
Written for Day 2 of Dart Basic.
*/3. Documentation Comments
Three slashes, ///, document the thing right below them. Editors show the text when you
hover over its name.
/// Prints a greeting for the given day.
void greet() {
print('Good morning!');
}4. Good Comments
Write comments that explain why, not what — the code already says what.
// Bad: prints the total
print(total);
// Good: shown before the receipt so the cashier can confirm it
print(total);Code Examples
Example 1 — Switching a Line Off
void main() {
print('Welcome to Dart Basic');
print('Lecture 005');
// print('This line is switched off');
/*
print('So is this one');
print('And this one');
*/
print('Goodbye!');
}Output
Welcome to Dart Basic
Lecture 005
Goodbye!"Commenting out" is a quick way to test a program without some lines — without deleting them. In IntelliJ, Ctrl + / (⌘ + / on macOS) comments or uncomments the selected lines.
Common Beginner Mistakes
1. Forgetting to close /* — without */, the rest of the file becomes a comment and you
get confusing errors far below.
2. Commenting every line — // print hello above print('hello') adds nothing. Comment
the reason, not the obvious.
3. Leaving old code commented out forever — once you are sure you don't need it, delete it.
Practice Questions
- Which symbol starts a single-line comment?
- How do you write a comment over several lines?
- What is special about
///? - What happens to a line that starts with
//when the program runs?
Practice Answers
//./* ... */.- It documents the code below it; editors show it on hover.
- Nothing — Dart ignores it.
Key Takeaways
//comments one line;/* */comments a block.///documents code for editors and tools.- Comment out lines to switch them off without deleting.
- Good comments explain why, not what.