Dart: Dart Fundamentals — Program Structure Comments and Code
Last updated: 2026-08-26
Syntax is the skeleton of code — standardized syntax habits determine the readability and maintainability of code.
1. What You Will Learn
- The
main()entry function and the program execution model - Semicolons, curly braces, and indentation conventions (dart format rules)
- Three types of comments: Line comments / Block comments / Documentation comments (
///) - An overview of keywords and reserved words
- The difference between statements and expressions
2. A Developer's Real Story
(1) Pain Point: Lack of Comments Leads to Unmaintainable Code
Charlie inherited a data processing script from a former colleague with absolutely no comments. Among 500 lines of code filled with magic numbers and abbreviated variable names, it took him 3 days to figure out that p stood for product and t for taxRate. Worse still, a critical tax calculation logic lacked documentation comments, causing a new colleague to mistakenly modify it, thinking it was a bug. This resulted in incorrect tax calculations for 2,000 orders and a direct financial loss of 50,000 USD.
(2) Solution with Standardized Syntax
Dart provides three types of comments. Combined with dart format for automatic formatting and dart analyze for static checking, you can write code that is structurally clear and well-commented.
/// Calculates the tax amount for an order.
///
/// Uses the regional tax rate and applies exemptions
/// for orders below the minimum threshold.
double calculateTax(double amount, double taxRate, {double exemptThreshold = 0}) {
// Apply exemption threshold
if (amount <= exemptThreshold) return 0;
/* Complex tax calculation logic
that may span multiple lines */
final taxableAmount = amount - exemptThreshold;
return taxableAmount * taxRate;
}
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
(3) Benefits
- Documentation comments can be automatically generated into API docs by
dart doc dart formatunifies the team's code style, eliminating formatting debates- Standardized naming + comments improve code maintainability by 3 times
3. Program Structure and the main Entry Point
(1) Program Execution Model
Every Dart program begins execution from the main() function. Dart uses a single-threaded event loop model but can achieve parallelism through Isolates.
graph TD
A[OS loads Dart VM] --> B[Find main function]
B --> C[Execute main body]
C --> D{Has async operations?}
D -->|No| E[Program exits]
D -->|Yes| F[Event loop runs]
F --> G[Process microtasks]
G --> H[Process events]
H --> I{More events?}
I -->|Yes| G
I -->|No| E
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
▶ Example
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
: Basic form of the main function
// Simplest main function
void main() {
print('DataPipeline starting...');
}
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
▶ Example
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
: Main function with arguments
// main with command line arguments
void main(List``<String>`` arguments) {
// arguments[0] is the first arg (not the program name)
print('Arguments received: $arguments');
print('Argument count: ${arguments.length}');
}
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
| main form | Signature | Usage |
|---|---|---|
| No arguments | void main() |
Simple scripts |
| With arguments | void main(List``<String>`` args) |
CLI tools |
| With return value | Future``<void>`` main() |
Async entry point |
4. Semicolons, Curly Braces, and Indentation
(1) Basic Syntax Rules
Dart uses semicolons ; to end statements and curly braces {} to enclose code blocks. Indentation is 2 spaces (enforced by dart format).
▶ Example
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
: Semicolons and curly braces
void main() {
// Each statement ends with semicolon
int orderCount = 1000;
double totalAmount = 50000.0;
// Block body requires curly braces
if (orderCount > 0) {
print('Processing $orderCount orders');
} else {
print('No orders to process');
}
}
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
| Rule | Description | dart format handling |
|---|---|---|
| Semicolon at the end | Every statement must end with ; |
Does not add automatically |
| Curly braces | if/for/while must use {} |
Auto-formats |
| Indentation | 2 spaces indent | Auto-corrects |
| Line width | Recommended within 80 characters | Not enforced |
5. Three Types of Comments
(1) Line Comments //
Used for single-line explanations, most commonly used.
▶ Example
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
: Line comments
void main() {
// Initialize the data pipeline
final maxRecords = 1000000; // Maximum records to process
// TODO: Add config file support
print('Max capacity: $maxRecords records');
}
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
(2) Block Comments /* */
Used for multi-line explanations or temporarily disabling code.
▶ Example
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
: Block comments
void main() {
/* This section handles the initial setup
of the DataPipeline configuration.
It reads from environment variables. */
final config = 'production';
/*
// Temporarily disabled for debugging
if (config == 'production') {
enableLogging();
}
*/
}
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
(3) Documentation Comments ///
Used to generate API documentation, supporting Markdown format.
▶ Example
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
: Documentation comments
/// Represents an e-commerce order with tax calculation.
///
/// This class models a single order from the DataPipeline
/// system, including amount, tax rate, and status.
///
/// Example:
/// ```dart
/// final order = Order(id: 'ORD-001', amount: 1500.0);
/// print(order.totalWithTax);
/// ```
class Order {
final String id;
final double amount;
Order({required this.id, required this.amount});
double get totalWithTax => amount * 1.08;
}
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
| Comment Type | Syntax | Purpose | Generates Documentation |
|---|---|---|---|
| Line comment | // |
Code explanations, TODOs | No |
| Block comment | /* */ |
Multi-line explanations, disabling code | No |
| Documentation comment | /// |
API documentation | Yes (dart doc) |
6. Keywords and Reserved Words
(1) Dart Keyword Classification
| Category | Keywords | Description |
|---|---|---|
| Declarations | class enum mixin extension typedef |
Type declarations |
| Modifiers | abstract sealed final const late static |
Modifiers |
| Control | if else for while do switch return |
Flow control |
| Exceptions | try catch finally throw rethrow |
Exception handling |
| Async | async await sync yield |
Asynchronous programming |
| Types | int double String bool dynamic void |
Built-in types |
| Null Safety | null late required |
Null Safety |
▶ Example
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
: Avoid using reserved words as identifiers
// Correct - use descriptive names
int orderCount = 100;
String customerName = 'Alice';
double taxRate = 0.08;
// Wrong - avoid reserved words as identifiers
// int class = 5; // Syntax error!
// String function = 'test'; // Syntax error!
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
7. Statements and Expressions
(1) Core Difference
Expressions have a return value; statements do not. This is fundamental to understanding Dart syntax.
graph TD A[Code Unit] --> B[Expression<br/>has value] A --> C[Statement<br/>no value] B --> B1[literal: 42] B --> B2[variable: count] B --> B3[operation: a + b] B --> B4[function call: max(1, 2)] C --> C1[if-else] C --> C2[for loop] C --> C3[return statement] C --> C4[variable declaration]
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
▶ Example
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
: Expression vs Statement
void main() {
// Expressions - produce values
int count = 100; // 100 is an expression
double price = 29.99; // 29.99 is an expression
double total = price * count; // price * count is an expression
bool isExpensive = total > 1000; // total > 1000 is an expression
// Statements - do not produce values
if (isExpensive) { // if statement
print('High value order'); // print call statement
}
// Dart 3: switch expression (expression!)
String label = switch (count) {
0 => 'empty',
<= 10 => 'small',
<= 100 => 'medium',
_ => 'large',
};
}
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
| Dimension | Expression | Statement |
|---|---|---|
| Return Value | Yes | No |
| Nesting | Can be nested in other expressions | Executed independently |
| Examples | a + b, x > 0 |
if, for, return |
| Dart 3 New Feature | switch expression | — |
8. Complete Example: DataPipeline Code Style Template
// ============================================
// DataPipeline - Code Style Template
// Demonstrates proper syntax, comments, and structure
// ============================================
/// Configuration for the DataPipeline processing engine.
///
/// Holds settings like maximum batch size, output format,
/// and whether to enable verbose logging.
class PipelineConfig {
/// Maximum number of records per processing batch.
final int batchSize;
/// Output format for generated reports.
final String outputFormat;
/// Enable detailed processing logs.
final bool verbose;
/// Creates a new pipeline configuration.
///
/// Default batch size is 10,000 records.
/// Default output format is 'json'.
PipelineConfig({
this.batchSize = 10000,
this.outputFormat = 'json',
this.verbose = false,
});
/// Returns a human-readable summary of the config.
String get summary =>
'Batch: $batchSize records, Format: $outputFormat, Verbose: $verbose';
}
/// Entry point for DataPipeline CLI tool.
void main(List``<String>`` arguments) {
// Step 1: Load configuration
final config = PipelineConfig(
batchSize: 50000,
outputFormat: 'csv',
verbose: true,
);
// Step 2: Display configuration
print('=== DataPipeline Configuration ===');
print(config.summary);
// Step 3: Process based on arguments
/* TODO: Implement actual data processing
- Read input source
- Transform records
- Write output report
*/
final recordCount = arguments.isNotEmpty ? int.tryParse(arguments[0]) ?? 0 : 0;
if (recordCount > 0) {
print('Processing $recordCount records...');
} else {
print('No records specified. Use: dart run bin/main.dart ``<record_count>``');
}
}
> **Output:** Run in local DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and the output may vary slightly depending on the SDK version.
Output (
dart run bin/main.dart 100000):
=== DataPipeline Configuration ===
Batch: 50000 records, Format: csv, Verbose: true
Processing 100000 records...
❓ FAQ
Q: Is a semicolon mandatory in Dart? A: Yes, every statement in Dart must end with a semicolon, unlike Python/Go where it can be omitted. This is the most common beginner mistake in Dart.
Q: When should I use line comments vs documentation comments? A: For public APIs (classes, public methods, public properties), use
///documentation comments. For internal implementation details, use//line comments.dart doconly processes documentation comments.
Q: Does
dart formatchange the code logic? A: No.dart formatonly adjusts whitespace and line breaks, without altering the code's semantics. You can confidently use--set-exit-if-changedin CI.
Q: Can
ifstatements in Dart omit curly braces? A: Syntactically, if followed by a single statement, curly braces can be omitted. However,dart formatwill automatically add them. It's strongly recommended to always use curly braces.
Q: What's the difference between a switch expression and a switch statement? A: A switch expression (Dart 3) has a return value and uses
=>branches. A switch statement has no return value and usescase:branches. The former is more concise; the latter is more flexible.
Q: Should I use
///or/** */for documentation comments? A: Dart officially recommends///. Although/** */is valid,///is the mainstream style in the Dart community, anddart formatalso formats using///.
Q: Can the
mainfunction return anint? A: Dart'smainreturn type isvoidorFuture``<void>``. The process exit code can be set using theexit()function fromdart:io`.
📖 Summary
- A Dart program starts execution from
main(), supporting both synchronous and asynchronous entry points. - Semicolons, curly braces, and 2-space indentation are Dart's basic syntax rules, automatically enforced by
dart format. - The three types of comments each serve a purpose:
//line comments,/* */block comments,///documentation comments (for generating API docs). - Keywords are categorized into 7 major groups: declarations, modifiers, control flow, exceptions, async, types, and null safety.
- Expressions have return values, statements do not — Dart 3's switch expression bridges this gap.
📝 Exercises
- Basic (Difficulty ⭐): Write a
mainfunction using each of the three comment types. Rundart doc .to see the effect of the generated documentation. - Intermediate (Difficulty ⭐⭐): Intentionally write a few sections of poorly formatted Dart code (mixed indentation, missing curly braces), then use
dart formatto auto-correct it. Compare the differences before and after. - Challenge (Difficulty ⭐⭐⭐): Write complete documentation comments (including description, parameter explanations, and example code) for a class containing 3 methods. Run
dart docto generate HTML documentation and review the result.