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.
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>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...
});
}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.
This proposal builds upon established patterns already used in the flutter/packages repository.
Here's an example of how code excerpts are used today:
- Cross file README code excerpts: packages/cross_file/README.md
- Cross file excerpts source code packages/cross_file/example/lib/readme_excerpts.dart