Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "dart-flutter",
"displayName": "Dart and Flutter",
"version": "1.0.7",
"version": "1.0.8",
"description": "Official Claude plugin for Dart and Flutter that installs Flutter/Dart Skills and Dart MCP server for building natively compiled, visually stunning applications for mobile, web, desktop, and embedded devices from a single codebase",
"author": {
"name": "Dart and Flutter",
Expand Down
2 changes: 1 addition & 1 deletion .codex-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "dart-flutter",
"version": "1.0.8",
"version": "1.0.9",
"description": "Official Codex plugin for Dart and Flutter that installs Flutter/Dart Skills and Dart MCP server for building natively compiled, visually stunning applications for mobile, web, desktop, and embedded devices from a single codebase.",
"author": {
"name": "Google LLC",
Expand Down
2 changes: 1 addition & 1 deletion .cursor-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "dart-flutter",
"displayName": "Dart and Flutter",
"version": "1.0.7",
"version": "1.0.8",
"description": "Official Cursor plugin for Dart and Flutter that installs Flutter/Dart Skills and Dart MCP server for building natively compiled, visually stunning applications for mobile, web, desktop, and embedded devices from a single codebase.",
"author": {
"name": "Dart and Flutter Team",
Expand Down
2 changes: 1 addition & 1 deletion skills/dart-migrate-to-checks-package/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ For any target test file:
..has((e) => e.message, 'message').equals('invalid input');

// NO (Passing a callback to sync throws will cause a compiler error!)
check(() => triggerSync").throws<ArgumentError>((it) => ...); // ERROR!
check(() => triggerSyncError()).throws<ArgumentError>((it) => ...); // ERROR!
```
- **Asynchronous** (`Subject<Future<T>>`): `.throws<E>()` returns
`Future<void>`. Because you cannot chain directly off a `Future<void>`, this
Expand Down
154 changes: 119 additions & 35 deletions skills/dart-use-doc-examples/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,96 +1,180 @@
---
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."
description: "Reference example code in dartdoc documentation comments and markdown files using the {@example} directive, with #region <name>, #endregion and #hide markers."
---

# Using Examples in Dartdoc
# Using Examples in Documentation

## 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)
* [3. Placement of example code](#3-placement-of-example-code)
* [4. Examples in markdown files](#4-examples-in-markdown-files)
* [5. Verification](#5-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.
When putting example code in documentation, prefer to write the examples as standalone `.dart` files and reference their contents with the `{@example}` directive.
This is better than inline example code, because standalone dart files are analyzed and linted, ensuring example code is maintained.

## 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]}`
**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):*
*Bad (inline example code):*
```dart
/// Makes a client service request to the backend.
///
/// ```dart
/// final client = Client();
/// client.send();
/// await client.get(Uri.parse('https://example.com'));
/// ```
```

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

The `{@example <path>}` directive is a block-directive and should be on its own line. The `<path>` is a URI relative to the current file,
it may use `../`, but may not reach outside the _package root_ (the folder containing `pubspec.yaml`).
If the `<path>` starts with `/`, it is relative to _package root_, this is often the preferred manner to reference example files.

> [!NOTE]
> The `<path>` uses forward slashes as separators on all platforms and URI encoded characters like `%20` to encode space.
> Absolute URIs (like `https://...`) are not supported.

## 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.
An example file often contains license headers, imports, setup, or `void main()` wrappers that you don't want in the documentation.
You can extract a specific _region_ of code by appending `#<region_name>` to the `{@example}` directive path, and wrapping that code
with `#region <region_name>` and `#endregion` comments in the target file.

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

void main() {
Future<void> main() async {
// #region request_snippet
final client = Client();
client.send();
await client.get(Uri.parse('https://example.com'));
// #endregion request_snippet
}
```

> [!NOTE]
> The `<region_name>` is only required on the `#region <region_name>` tag.
> Writing `#endregion <region_name>` as above is merely good practice.

**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.
Regions can be closed and reopened (using the same region name), this can be used to hide a block of code in the middle of a region.
To hide a single line use `#hide`.

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

Future<void> main() async {
// #region request_snippet
// Make a request
final client = Client(); // #hide
// #endregion request_snippet
startFakeServer()
..domain = 'example.com';
// #region request_snippet
await client.get(Uri.parse('https://example.com'));
// #endregion request_snippet
}
```

**Dart Code:**
**Dartdoc Usage:**
```dart
final mockServer = startServer(); // #hide
final data = await fetch(mockServer.url);
/// Connects the client to the server and sends a request.
///
/// {@example /example/client.dart#request_snippet}
```
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:
Fenced code block rendered by `dartdoc`:
```dart
// Make a request
await client.get(Uri.parse('https://example.com'));
```

* **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 -->`).
> [!NOTE]
> `#hide`, `#region`, and `#endregion` markers are only processed (and removed) when referencing a specific region (e.g., `{@example file.dart#region_name}`).
> If referencing an entire file (e.g., `{@example file.dart}`) these markers are ignored and the file is embedded as it appears (including any `// #hide` markers).

The `#region <region_name>`, `#endregion` and `#hide` markers are format-agnostic, and will be processed as text.
Meaning they can appear in Dart, YAML, HTML comments (`<!-- #region -->`) or inside strings (granted using region markers in strings is discouraged).

## 3. Placement of example code

These are guidelines for where to place example code.

* (A) Dedicated file in `example/`, like `example/say_hello.dart`:
* Suitable for small simple examples (like call function and print results).
* Pros: Easy for a user to run the example file on their machine (or dartpad.dev).
* Cons: Nothing tests that the example does what it claims when executed.

* (B) Region in a `test/` file, like `test/example/request_example_test.dart`:
```dart
import 'package:test/test.dart';
import 'package:http/http.dart';

void main() {
test('request example.com', () async {
final client = Client();
// #region request_snippet
await client.get(Uri.parse('https://example.com'));
// #endregion request_snippet
});
}
```
* Suitable for complex examples that have setup and where testing is warranted.
* Pros: Package author will be testing the example code with `dart test` (typically also in CI).
* Cons: Package consumers can't easily run the example code.

* (C) Dedicated example app in `example/`, like `example/my_demo_app/`:
* Suitable when an example is a full app (like a flutter app) or needs dependencies the root package doesn't want.
* Pros: Enables high fidelity examples, easy for users to run on their machine (or dartpad.dev).
* Cons: An example app might need its own test suite (like `example/my_demo_app/test/`), which you might want to run in CI.

`dart analyze` will run analysis on all files in a project, so (A), (B) and (C) all get static analysis errors and lints surfaced.
This helps ensure that example code stays up-to-date as the package API changes. In many cases (A) is the simplest way to write examples.
The biggest downside of doing (A) is that nothing tests the examples.

Use your best judgement to decide where to put an example (A), (B) or (C).
Regardless of where you put it, you'll often put it in a different top-level folder than the code referencing it,
so prefer using package root relative `/` paths in `{@example /...}` directives.

## 4. Examples in markdown files
Similar to `{@example}` in documentation comments, you can use `package:snippets` to embed examples from external files in a markdown file.
One simply writes a _fenced markdown code block_ with `@example <path>[#<region>]` in the _info-string_, as illustrated below:

~~~md
```dart @example /example/example.dart#greeting
final message = 'Hello, world!';
print(message);
```
~~~

## 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:
Then run `dart run snippets@ update` which will update the contents of the _fenced code block_ in the file on disk.
(if doing this, consider using `dart run snippets@ validate` in CI. Note `dart run snippets@` is a _global run_, so no dependency is needed).

* **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.
See also: https://pub.dev/packages/snippets

## 6. Verification
## 5. Verification
After injecting examples:
1. Run `dart analyze` on the example files to ensure the hidden setup code compiles.
1. Run `dart analyze` on the example files to ensure there are no analysis errors.
2. (Optional) Run `dart doc` to verify that dartdoc successfully parsed the directive without throwing a "Failed to read file" or "missing region" warning.
3. (If applicable) Run `dart run snippets@ validate` to verify that examples in markdown files are up-to-date.
10 changes: 6 additions & 4 deletions skills/dart-use-path-package/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ description: >-
Cross-platform file and directory path manipulation, segment splitting, extension extraction, and context conversion using `package:path` and `package:file`. Use when writing, inspecting, joining, splitting, or refactoring file paths, directory names, or extensions, or replacing raw string path operations (`.split('/')`, `'$dir/$file'`, `.endsWith('.ext')`, `.replaceAll('\\', '/')`). Don't use for HTTP network URI routing, database query strings, or non-path string processing.
metadata:
model: models/gemini-3.1-pro-preview
last_modified: Wed, 23 Sep 2026 22:10:00 GMT
last_modified: Fri, 13 Nov 2026 03:41:00 GMT
---

# Safe Cross-Platform Path Manipulation in Dart
Expand Down Expand Up @@ -34,9 +34,10 @@ metadata:
* **POSIX-Only Tools & Static Subpath Greppability**: In codebases exclusively targeting Linux/macOS (or when joining a dynamic base path to a known static subpath), decomposing 5–6 static segments into separate arguments (`p.join(home, '.local', 'share', 'app', 'bin', 'config.json')`) causes `dart format` to wrap across 6–8 vertical lines and **destroys substring greppability** (`grep` / `code_search` for `.local/share/app/bin`).
* **Rule for POSIX Targets**: Prefer **2-argument boundary joining** (`p.join(home, '.local/share/app/bin/config.json')`). This prevents duplicate-slash bugs (`//`) at variable boundaries while preserving single-line readability and exact string searchability.

### Normalization vs. Canonicalization (`p.normalize` vs. `p.canonicalize`)
* `p.normalize(path)` resolves `.` and `..` segments purely lexically without consulting the filesystem or standardizing case.
* When deduplicating directory paths or comparing physical file identity across symlinks, relative roots, or case-insensitive filesystems, use `p.canonicalize(path)`.
### Lexical Canonicalization vs. Physical Symlink Resolution
* `p.normalize(path)` resolves `.`, `..`, and redundant separators purely lexically while preserving relative vs. absolute form and case.
* `p.canonicalize(path)` converts to an absolute path, normalizes segments, and standardizes ASCII case on Windows—still purely lexically (`package:path` never consults the filesystem and **does not resolve symlinks**).
* When comparing physical file or directory identity on disk or keying caches across symlinks (such as macOS `/tmp` -> `/private/tmp`) and relative CLI flags (`-o out`), resolve symlinks via `Directory(path).resolveSymbolicLinksSync()` or `File(path).resolveSymbolicLinksSync()` (or `fileSystem.directory(path).resolveSymbolicLinksSync()` in `package:file`). Unlike lexical `p.canonicalize(path)`, `resolveSymbolicLinksSync()` throws a `FileSystemException` if the path does not exist yet—ensure the target exists first or fall back to `p.canonicalize(path)` / `directory.absolute.path` on `FileSystemException`.

### Strip Location Specifiers & Convert URIs Safely
* Strings formatted as `<path>:<line>-<col>` or `<path>:<line>` are not pure file paths. Passing them directly to `p.normalize` or `Uri.parse` causes bugs (on Windows, `Uri.parse` mistakes `C:` for a URI scheme and `:line` for a port).
Expand Down Expand Up @@ -197,6 +198,7 @@ String insertContentHash(String filename, String hash) {
- [ ] Replace `.endsWith('.ext')` on file paths with `p.extension(path) == '.ext'`.
- [ ] Replace manual dot-index slicing with `p.withoutExtension(path)` and `p.extension(path, [level])`.
- [ ] Verify that code using `package:file` accesses `fileSystem.path` instead of global `p.*`.
- [ ] Use `resolveSymbolicLinksSync()` (catching `FileSystemException` when paths may not exist yet) instead of lexical `p.canonicalize(path)` when comparing physical on-disk paths across symlinks.
- [ ] Ensure Git paths, `.gitignore` entries, and symlink targets use `p.posix` forward slashes.

---
Expand Down
30 changes: 29 additions & 1 deletion skills/dart-use-pattern-matching/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ description: >-
type promotion (use `is`), or basic collection filtering.
metadata:
model: models/gemini-3.1-pro-preview
last_modified: Tue, 13 Oct 2026 19:45:00 GMT
last_modified: Fri, 13 Nov 2026 02:48:00 GMT
---
# Implementing Dart Patterns

Expand Down Expand Up @@ -225,6 +225,34 @@ String? resolveAllowedAssetSubpath(List<String> segments) {
}
```

### Compound Filename Classification (Replacing Multi-Dot RegExp)
Split basenames on `'.'` and switch on list patterns with rest elements (`...`)
and inline `when` guards (such as `int.tryParse`) instead of maintaining nested
regular expressions that risk over-matching sibling files. See
[examples/filename_patterns.dart](examples/filename_patterns.dart) for an
executable implementation.

```dart
enum BuildArtifact {
entrypoint,
sourceMap,
deferredPart,
supportRuntime;

static BuildArtifact? tryParse(String name) => switch (name.split('.')) {
['main', 'dart', 'js'] => entrypoint,
['main', 'dart', 'js', 'map'] => sourceMap,
// Matches numbered chunks like 'main.dart.1.part.js'.
['main', 'dart', final part, ..., 'part', 'js']
when int.tryParse(part) != null =>
deferredPart,
// Stays distinct instead of being swallowed by 'main.dart.*.js'.
['main', 'dart', 'support', 'js'] => supportRuntime,
_ => null,
};
}
```

### Algebraic Data Types (Sealed Classes)
Use Object patterns with switch expressions to handle family types exhaustively.

Expand Down
Loading
Loading