Skip to content

Instantly share code, notes, and snippets.

@loic-sharma
Last active March 24, 2026 18:29
Show Gist options
  • Select an option

  • Save loic-sharma/9a698cfcb047bf30d3c2aaacdf957137 to your computer and use it in GitHub Desktop.

Select an option

Save loic-sharma/9a698cfcb047bf30d3c2aaacdf957137 to your computer and use it in GitHub Desktop.
Code excerpts for API references

Proposal: Markdown Code Excerpts for API References

Overview

Currently, the Flutter framework uses snippet blocks in API reference docs to showcase example code. We are considering switching to Markdown code blocks.

To ensure these these examples don't "bit rot", we can use "code excerpts" to synchronize the examples to validated test files.

The workflow

1. The source file

In the source file (e.g., packages/material_ui/lib/src/circle_avatar.dart), a standard Markdown code block is used. A special comment identifies it is a managed excerpt:

/// <example>
///
/// If the avatar is to have an image, the image should be specified in the
/// [backgroundImage] property:
///
// @code-excerpt "../../tests/circle_avatar_test.dart (basic)"
/// ```dart
/// final avatar = CircleAvatar(
///   backgroundImage: NetworkImage(userAvatarUrl),
/// );
/// ```
///
/// </example>

2. The test file

In the corresponding test file (e.g., packages/material_ui/test/circle_avatar_test.dart), the code is wrapped in a "docregion" tag. This code is executed during standard test runs:

void main() {
  testWidgets('CircleAvatar basic example', (WidgetTester tester) async {
    // #docregion basic
    final avatar = CircleAvatar(
      backgroundImage: NetworkImage(userAvatarUrl),
    );
    // #enddocregion basic
     
    // Test the widget works as expected here...
  });
}

3. The CI check

The CI checks that code excerpts are up-to-date: script/tool/lib/src/readme_check_command.dart.

If a code excerpt does not match the test file, the CI check fails. The pull request cannot be merged until the code excerpt is fixed.

Prior art

This proposal builds upon established patterns already used in the flutter/packages repository.

Here's an example of how code excerpts are used today:

  1. Cross file README code excerpts: packages/cross_file/README.md
  2. Cross file excerpts source code packages/cross_file/example/lib/readme_excerpts.dart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment