CodeBlanks Logo Icon CodeBlanks

Example code

Learn example code in documentation.

Example code

Example code in doc comments shows the reader how to use the API. A Markdown code block starts with ```dart and ends with ```.

Each line must start with ///; so you write /// ```dart and add lines like /// square(4); below it.

dartdoc renders the code block as syntax-highlighted HTML; this clearly explains how to use the API.

An example code example

Typical usage: under /// Example: you write /// ```dart, then /// final sum = add(2, 3); and finally /// ```.

The code block should contain real working code; comments are added with //. dartdoc highlights it as-is.

Pick short, meaningful examples; long ones bloat the docs and reduce readability.

Practice A doc comment with example code

Write int square(int n) => n * n;. Add a doc comment above it: first line /// Example:, second line /// ```dart, third line /// square(4); // 16, fourth line /// ```. In main call print(square(5)).

Starter code

main.dart
// Write the square function and its example code block

void main() {
  // print the result of square(5)
}

Sample solution

main.dart
/// Example:
/// ```dart
/// square(4); // 16
/// ```
int square(int n) => n * n;

void main() {
  print(square(5));
}

Expected output

25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Code block start

Question
/// ____dart
Answer
/// ```dart

Explanation: ```dart starts a code block.

2 Example code parts

Term Meaning
```dart Code block
/// Doc comment
// 16 Inline comment
Example: Label

3 How does an example code block start?

  • ```dart Correct answer
  • <code>
  • [code]
  • //code

Explanation: ```dart opens a Markdown code block.

All lessons in Intermediate