К основному содержанию
скилл Claude Code CX Codex Cursor GitHub Copilot

dart-use-doc-examples — скилл для Claude Code: вставка примеров

Учит агента вставлять внешние примеры кода в Dartdoc через директиву {@example} вместо inline-блоков.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add flutter/agent-plugins --skill dart-use-doc-examples -a claude-code
Открыть на GitHub

Что делает dart-use-doc-examples

Скилл объясняет, как подключать файлы .dart с примерами в документацию методов и классов через {@example}. Агент узнаёт синтаксис директивы, работу с регионами (#region/#endregion) для извлечения нужных фрагментов и маркер #hide для скрытия строк setup-кода, которые нужны компилятору, но не читателю.

Путь к файлу можно задать от корня пакета (/example/client.dart) или относительно текущего файла. Регионы позволяют вырезать конкретный блок, спрятав импорты и обёртки void main(). Строки с #hide полностью исчезают из сгенерированной документации. После вставки примеров скилл советует проверить их через dart analyze, чтобы скрытый код компилировался.

Какие задачи решает

  • вставить внешний файл с примером в комментарий Dartdoc
  • извлечь конкретный регион кода, спрятав импорты и setup
  • скрыть строку setup-кода от читателя через #hide
  • разрешить путь к примеру от корня пакета или относительно файла
  • проверить, что скрытый код компилируется через dart analyze

Примеры запросов агенту

  • Добавь пример из `/example/client.dart` в документацию этого метода через `{@example}`
  • Извлеки только блок `request_snippet` из файла примера, спрячь импорты
  • Спрячь строку с `mockServer` в примере документации через `#hide`

Как установить dart-use-doc-examples

1Через Skills CLI (Vercel)

npx skills add flutter/agent-plugins --skill dart-use-doc-examples -a claude-code

2Вручную: положить файлы

~/.claude/skills/dart-use-doc-examples/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/dart-use-doc-examples/

Из того же набора14

Весь набор →
flutter-apply-architecture-best-practices flutter Скилл раскладывает Flutter-приложение по слоям UI, Logic и Data. Пригодится для нового проекта или рефакторинга кода. Claude Code CX Codex Cursor +1 43 000установок flutter-build-responsive-layout flutter Скилл обучает агента строить адаптивные интерфейсы Flutter под экраны телефонов и десктопов. Он задаёт правила работы с LayoutBuilder и MediaQuery. Claude Code CX Codex Cursor +1 42 300установок flutter-add-widget-test flutter Скилл помогает писать компонентные тесты Flutter с помощью WidgetTester. Проверяет, как виджет отображается и реагирует на касания, скролл и ввод текста. Claude Code CX Codex Cursor +1 39 000установок flutter-add-integration-test flutter Скилл настраивает интеграционные тесты во Flutter через пакет integration_test. Он переносит действия из MCP-сервера в готовые тестовые сценарии. Claude Code CX Codex Cursor +1 38 000установок flutter-setup-declarative-routing flutter Настраивает декларативную маршрутизацию Flutter через go_router: маршруты по URL, вложенную навигацию и глубокие ссылки для веба и мобильных платформ. Claude Code CX Codex Cursor +1 37 600установок flutter-implement-json-serialization flutter Скилл учит агента создавать Dart-модели с методами fromJson и toJson через библиотеку dart:convert. Пригодится при ручном разборе простых структур данных в Flutter. Claude Code CX Codex Cursor +1 37 200установок flutter-add-widget-preview flutter Скилл учит агента создавать интерактивные превью виджетов во Flutter через package:flutter/widget_previews.dart. Пригодится для изолированной вёрстки UI без сборки всего приложения. Claude Code CX Codex Cursor +1 36 600установок flutter-setup-localization flutter Скилл автоматизирует инициализацию поддержки многоязычности в Flutter-проекте. Добавляет зависимости, включает генерацию кода и создаёт конфиг для работы с .arb-файлами. Claude Code CX Codex Cursor +1 36 600установок

Похожие

book-study sanyuan0704 Ведёт изучение книг по главам: собирает заметки, проверяет понимание и возвращает материал на повторение. Пригодится для чтения с планом и вопросами. Claude Code CX Codex Cursor +1 3 500установок fact-check leonardomso Проверяет техническую точность обучающих статей по JavaScript: сверяет примеры кода, документацию MDN и спецификацию ECMAScript. Claude Code CX Codex Cursor +1 331установок file-conversion Seth Hobson Конвертирует локальные медиафайлы, документы и таблицы без отправки во внешние API. Работает через FFmpeg, ImageMagick, Pandoc и LibreOffice. Claude Code CX Codex Cursor 3 100установок concept-workflow leonardomso Скилл координирует создание обучающих страниц по JavaScript от подбора материалов до тестов и проверки фактов. Пригодится для наполнения базы знаний или репозитория 33-js-concepts. Claude Code CX Codex Cursor +1 322установок resource-curator leonardomso Скилл находит, проверяет и упорядочивает учебные материалы для справочников по JavaScript. Пригодится при наполнении страниц тем или чистке старых ссылок. Claude Code CX Codex Cursor +1 319установок write-docs tldraw Скилл для написания и обновления документации SDK tldraw. Помогает создавать статьи, обновлять существующие доки и следовать стилю проекта. Claude Code CX Codex Cursor +1 486установок grill-with-docs Matt Pocock Скилл проводит жёсткое интервью по плану или дизайну и по ходу создаёт ADR и глоссарий. Подойдёт перед началом сложной разработки. Claude Code 1 219 756установок skill-creator официальный anthropics Помогает создать новый скилл, доработать существующий и проверить результат через тестовые промпты и оценки. Claude Code Claude.ai 414 180установок

Вопросы о dart-use-doc-examples

Как установить dart-use-doc-examples в Claude Code?

Выполни команду npx skills add flutter/agent-plugins --skill dart-use-doc-examples -a claude-code в терминале проекта.

Что делает dart-use-doc-examples?

Скилл учит агента вставлять внешние примеры кода в Dartdoc через директиву {@example}, скрывать setup-код маркером #hide и извлекать конкретные регионы из файлов примеров.

Как показать в документации только часть файла с примером?

Оберни нужный фрагмент комментариями #region имя_региона и #endregion имя_региона, затем вызови {@example /путь/к/файлу.dart#имя_региона} в Dartdoc.

Исходный текст

SKILL.md · BSD-3-Clause
---
name: dart-use-doc-examples
description: "How to inject external code examples into Dartdoc using the {@example} directive, and how to filter those files using #hide, #region, and #endregion tags."
---

# Using Examples in Dartdoc

## Contents
*   [1. The `{@example}` Directive](#1-the-example-directive)
*   [2. Using Regions](#2-using-regions)
*   [3. Hiding Setup Code](#3-hiding-setup-code)
*   [4. Marker Filtering Rules](#4-marker-filtering-rules)
*   [5. Placement and Path Resolution](#5-placement-and-path-resolution)
*   [6. Verification](#6-verification)

When writing documentation that requires multi-line code examples, you should generally extract those examples into standalone `.dart` files and inject them using the `{@example}` directive, rather than writing them inline inside `///` comments. This ensures the examples can be analyzed, linted, and executed.

## 1. The `{@example}` Directive
The `{@example}` directive parses an external file and resolves it into a fenced Markdown code block in the generated documentation.

**Syntax:** `{@example <path>[#<region>] [lang=LANGUAGE] [indent=keep|strip]}`

*   **`<path>`**: The path to the file. A leading `/` evaluates from the package root. Otherwise, it is relative to the current file.
*   **`lang`**: The language for the markdown fence. Auto-detected from the file extension (e.g., `dart`), but can be explicit (e.g., `lang=text`).
*   **`indent`**: `strip` (default) aggressively removes shared leading indentation from the code block.

*Bad (Inline Markdown):*
```dart
/// Makes a client service request to the backend.
///
/// ```dart
/// final client = Client();
/// client.send();
/// ```
```

*Good (External File Injection):*
```dart
/// Makes a client service request to the backend.
///
/// {@example /example/client_request.dart}
```

## 2. Using Regions
Often, an external example file contains imports, setup, or `void main()` wrappers that you don't want to show in the documentation. You can extract a specific block of code by appending `#<region>` to the `{@example}` directive path, and wrapping that code with `#region` and `#endregion` comments in the target file.

**Dart Code (e.g., `/example/client.dart`):**
```dart
import 'package:http/http.dart';

void main() {
  // #region request_snippet
  final client = Client();
  client.send();
  // #endregion request_snippet
}
```

**Dartdoc Usage:**
```dart
/// Connects the client to the server and sends a request.
///
/// {@example /example/client.dart#request_snippet}
```

## 3. Hiding Setup Code
If there is a specific line of code within your extracted region that is necessary for the compiler/analyzer to pass but irrelevant (or distracting) for the documentation reader, append `#hide` to that line.

**Dart Code:**
```dart
final mockServer = startServer(); // #hide
final data = await fetch(mockServer.url);
```
In the generated documentation, only `final data = await fetch(mockServer.url);` will be visible. The line with `#hide` is completely dropped.

## 4. Marker Filtering Rules
When working with `#hide`, `#region`, and `#endregion` markers, you must follow these two technical constraints:

*   **Region Required:** The markers are only processed and stripped when you target a specific region suffix (e.g., `{@example file.dart#region_name}`). If you inject an entire file without a region suffix, the file is embedded exactly as it appears in the source, including any marker text like `// #hide`.
*   **Format Agnosticism:** The marker system is completely format-agnostic. Dartdoc simply runs a regex to strip lines containing the marker strings, meaning it works identically in non-Dart files (e.g., inside YAML comments `# #region` or HTML comments `<!-- #region -->`).

## 5. Placement and Path Resolution
The `{@example}` directive is a block-level directive. It must appear on its own line prefixed with `///`. Its internal `<path>` parser follows strict URI reference rules:

*   **Package-Root Paths (`/`)**: Paths starting with a leading slash automatically resolve directly to the root of the Dart package. Use this when the destination file is deep.
    *   *Example:* `{@example /test/data/sample.txt}` exactly maps to `<package_root>/test/data/sample.txt`.
*   **Relative Paths**: Paths without a leading slash resolve relative to the directory of the file containing the doc comment.
    *   *Example:* `{@example ../utils/demo.dart}`
*   **Boundary Enforcement:** Using `..` segments to traverse upward is perfectly acceptable, but dartdoc natively stops directory traversal at the package root (it will never escape the package).
*   **No Network URLs:** Absolute URIs (e.g., starting with `https://`) are strictly not supported. The example file *must* sit natively somewhere in the local filesystem.
*   **Separators & Encoding:** Because dartdoc resolves the path as a URI, you must always use forward slashes (`/`) as folder separators (even on Windows). You can natively include URI-encoded characters (like `%20` for spaces) as permitted by URI reference rules.

## 6. Verification
After injecting examples:
1.  Run `dart analyze` on the example files to ensure the hidden setup code compiles.
2.  (Optional) Run `dart doc` to verify that dartdoc successfully parsed the directive without throwing a "Failed to read file" or "missing region" warning.

© flutter · BSD-3-Clause · flutter/agent-plugins

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой