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


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.

DART
/// 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;
}
TEXT 📖 Display only
> **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


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.

100%
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
TEXT 📖 Display only
> **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

TEXT 📖 Display only
> **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

DART
// Simplest main function
void main() {
  print('DataPipeline starting...');
}
TEXT 📖 Display only
> **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

TEXT 📖 Display only
> **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

DART
// 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}');
}
TEXT 📖 Display only
> **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

TEXT 📖 Display only
> **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

DART
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');
  }
}
TEXT 📖 Display only
> **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

TEXT 📖 Display only
> **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

DART
void main() {
  // Initialize the data pipeline
  final maxRecords = 1000000; // Maximum records to process

  // TODO: Add config file support
  print('Max capacity: $maxRecords records');
}
TEXT 📖 Display only
> **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

TEXT 📖 Display only
> **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

DART
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();
  }
  */
}
TEXT 📖 Display only
> **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

TEXT 📖 Display only
> **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

DART
/// 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;
}
TEXT 📖 Display only
> **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

TEXT 📖 Display only
> **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

DART
// 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!
TEXT 📖 Display only
> **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.

100%
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]
TEXT 📖 Display only
> **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

TEXT 📖 Display only
> **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

DART
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',
  };
}
TEXT 📖 Display only
> **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

DART
// ============================================
// 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>``');
  }
}
TEXT 📖 Display only
> **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):

TEXT 📖 Display only
=== 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 doc only processes documentation comments.

Q: Does dart format change the code logic? A: No. dart format only adjusts whitespace and line breaks, without altering the code's semantics. You can confidently use --set-exit-if-changed in CI.

Q: Can if statements in Dart omit curly braces? A: Syntactically, if followed by a single statement, curly braces can be omitted. However, dart format will 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 uses case: 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, and dart format also formats using ///.

Q: Can the main function return an int? A: Dart's main return type is void or Future``<void>``. The process exit code can be set using the exit()function fromdart:io`.


📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Write a main function using each of the three comment types. Run dart doc . to see the effect of the generated documentation.
  2. Intermediate (Difficulty ⭐⭐): Intentionally write a few sections of poorly formatted Dart code (mixed indentation, missing curly braces), then use dart format to auto-correct it. Compare the differences before and after.
  3. Challenge (Difficulty ⭐⭐⭐): Write complete documentation comments (including description, parameter explanations, and example code) for a class containing 3 methods. Run dart doc to generate HTML documentation and review the result.

← Previous Lesson | Next Lesson →

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏