
dart-build-cli-app
Architectural patterns, entrypoint structure, exit codes, stream routing, and subprocess spawning for Dart command-line interface (CLI) applications. Use when building CLI tools, console utilities, scripts, argument parsing with package:args (ArgParser or CommandRunner), handling exit codes, configuring executables in pubspec.yaml, spawning Dart subprocesses, or compiling native CLI binaries. Don't use for Flutter UI widgets, web applications, or standalone HTTP backend servers.
- Installs
- 14.2K
- Last 24h
- +179
- Trending rank
- #1338
- Security
- Pass
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/flutter/agent-plugins --skill dart-build-cli-app- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads dart-build-cli-app automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
Security audits
Independent scans of the skill's instructions and bundled files.
SKILL.md
The instructions your agent reads when the skill is triggered.
Building Dart CLI Applications
Contents
- 1. Core Architecture & Process Lifecycle
- 2. Streams, Diagnostics & Formatting
- 3. Project Configuration & Packaging
- 4. Argument Parsing & Command Routing
- 5. Native Async & Modern Stack Traces
- 6. Subprocess Spawning & AOT Resilience
- 7. Signal Handling & Terminal Teardown
- 8. Testing CLI Applications
- 9. Modern Compilation & Distribution
- 10. Workflows & Audit Checklist
- References & Examples
1. Core Architecture & Process Lifecycle
Avoid Destructive Exits (exit(N))
Calling dart:io's exit(int code) invokes Platform::Exit(code) in the C++ runtime. It immediately terminates the OS process without unwinding the Dart stack:
- Debugger Disconnect: When launched with
--pause-isolates-on-exit, the VM Service pauses isolates before shutdown to allow IDE inspection.exit()terminates the OS process before the VM Service can pause or inspect state. - Coverage Loss:
package:coveragequeries execution lines over VM Service RPCs during the paused-on-exit state.exit()destroys the process before RPC extraction, yielding 0% coverage. - Buffer Truncation:
stdoutandstderrare buffered asynchronousIOSinkstreams.exit()drops unflushed bytes. - Resource Leaks:
finallyblocks (closing locks, deleting temp directories) are bypassed.
Rule: Avoid calling exit(code) directly during normal execution; set exitCode = code or return an integer exit code from CommandRunner<int> (from package:args) and allow the asynchronous main() function to return naturally. Do not call exit() on unhandled errors; throw an unhandled Error or exception so the runtime unwinds cleanly and exits with a non-zero status.
Standard POSIX exit codes (/usr/include/sysexits.h):
0: Success (EX_OK/ExitCode.success.code)64: Command-line usage error (EX_USAGE/ExitCode.usage.code)65: Data format error (EX_DATAERR/ExitCode.data.code)70: Internal software crash (EX_SOFTWARE/ExitCode.software.code)78: Configuration error (EX_CONFIG/ExitCode.config.code)
Note: Prefer importing package:io/io.dart and using ExitCode constants
(e.g., ExitCode.usage.code, ExitCode.software.code) rather than magic
integer literals. For minimal standalone scripts without package dependencies,
standard POSIX integer literals (0, 64, 70) may be used.
import 'dart:io';
import 'package:args/command_runner.dart';
import 'package:io/io.dart' show ExitCode; // Provides standard POSIX ExitCode constants
Future<void> main(List<String> args) async {
final runner = CommandRunner<int>('tool', 'CLI tool description.');
try {
final status = await runner.run(args);
exitCode = status ?? ExitCode.success.code;
} on UsageException catch (e) {
stderr
..writeln(e.message)
..writeln(e.usage);
exitCode = ExitCode.usage.code;
}
}
The Thin Entrypoint Pattern (bin/ vs. lib/src/)
Keep bin/*.dart files strictly as minimal entrypoint trampolines (instantiate runner, pass args, await exit code). Place all command definitions, argument parsers, formatters, and business logic inside lib/src/.
- Rationale: Code in
bin/cannot be cleanly imported viapackage:URIs. Moving logic intolib/src/allows the entire command runner, subcommand hierarchy, and business logic to be unit-tested in-memory in milliseconds (< 2ms) without spawning OS subprocesses.
// bin/my_cli.dart — Thin entrypoint trampoline
import 'dart:io';
import 'package:my_cli/src/cli.dart';
Future<void> main(List<String> args) async {
exitCode = await runCli(args);
}
2. Output, Diagnostics & Formatting
- Data vs. Diagnostics: Write intended program results and machine-readable data exclusively to
stdout. Write warnings, error messages, and debug logs exclusively tostderr. - The Error Usage Rule: When an argument parsing or mandatory option error
occurs (
FormatException,UsageException, orArgumentErrorthrown when accessing a missingmandatory: trueoption viaresults.option(...)), both the error message and the usage text must write tostderr, and exit code64(EX_USAGE/ExitCode.usage.code) must be returned.stdoutshould ONLY receive usage help when the user explicitly requests it via--helpor-h. - No
print()in Error Handlers:print()routes tostdout. Usestderr.writeln()for all failure notifications. For standard output, preferstdout.writeln()overprint()to comply with theavoid_printlint rule (unlessanalysis_options.yamlexplicitly configuresavoid_print: false). - Terminal Capability Detection &
NO_COLOR: Verifystdout.hasTerminal,stdout.supportsAnsiEscapes, and!Platform.environment.containsKey('NO_COLOR')before emitting ANSI color or cursor escape codes:bool get useAnsi => stdout.hasTerminal && stdout.supportsAnsiEscapes && !Platform.environment.containsKey('NO_COLOR'); - Machine-Readable Modes: When
--jsonor--machineflags are passed, format data as JSON tostdoutand route logs tostderr.
3. Project Configuration & Packaging
Scaffolding & Pubspec Executable Mapping (executables:)
Scaffold new command-line projects using dart create -t console <package_name>, which initializes the standard bin/ and lib/ layout. Always declare executables in pubspec.yaml under executables: to map command names to scripts in bin/, enabling clean invocation via dart run <command> (without specifying bin/...dart) and configuring global binary symlinks for dart install:
name: my_cli
description: High-performance CLI tool.
version: 1.0.0
executables:
my_cli: # Maps to bin/my_cli.dart
secondary_cmd: helper # Maps to bin/helper.dart
Single-Source Versioning (package:build_version)
Avoid hardcoding --version strings in bin/*.dart or manually synchronizing constant files. Use package:build_version to generate lib/src/version.dart containing const packageVersion = 'x.y.z'; directly from pubspec.yaml during builds.
Caching Conventions
Store transient cache files in .dart_tool/<package_name>/. Never write persistent cache files directly to the project root.
4. Argument Parsing & Command Routing
Import package:args to manage command-line arguments:
- Simple Scripts: Use
ArgParserdirectly withaddFlag()andaddOption(). - Multi-Command Tools: Implement
CommandRunner<int>and extendCommand<int>for each subcommand, returning POSIX exit codes directly. - Type-Safe Accessors: Use
results.flag('name'),results.option('name'), andresults.multiOption('name')(available inpackage:args2.5+) instead of map indexingoperator []to eliminate manual type casts (as bool,as String?). - Complex Options Models: For applications with extensive flags, use
package:build_clito generate strongly-typed options classes. Leverage named default overrides (e.g.{String? hostDefaultOverride}) to cleanly merge configuration files with CLI flags.
5. Native Async & Modern Stack Traces
- Avoid
Chain.capture(): The Dart VM natively preserves asynchronous stack frames acrossawaitsuspension points.Chain.capturewraps the event loop in custom Zones, incurring substantial allocation overhead and trapping errors across Zone boundaries. - Sanitize with
Trace.from(st).terse: Use static utilities frompackage:stack_traceon uncaught errors without capturing zones:
import 'dart:io';
import 'package:io/io.dart' show ExitCode;
import 'package:stack_trace/stack_trace.dart';
Future<void> runMain(List<String> args) async {
try {
await executeLogic(args);
exitCode = ExitCode.success.code;
} catch (e, st) {
stderr.writeln('Fatal error: $e');
if (args.contains('-v') || args.contains('--verbose')) {
stderr.writeln(Trace.from(st).terse);
}
exitCode = ExitCode.software.code;
}
}
6. Subprocess Spawning & AOT Resilience
When spawning Dart SDK subprocesses or executing other Dart tools (e.g., dart format, dart test, build_runner):
- Do not assume
Platform.resolvedExecutableorPlatform.executablepoints to thedartcommand-line executable: In standalone AOT-compiled binaries (dart install/dart compile exe),resolvedExecutablepoints to the compiled application binary itself, causing recursive self-invocation loops or flag rejection crashes. - Use
package:cli_util: Resolve the Dart SDK executable usingcli_util.dartExecutableorcli_util.sdkPathinstead of writing custom PATH or directory scrapers. - See version requirements and detailed technical guide in references/aot_sdk_discovery.md.
7. Signal Handling & Terminal Teardown
If your CLI alters terminal modes, displays spinners, or opens listening sockets:
- Windows Signal Guard: On Windows,
ProcessSignal.sigterm.watch()throwsUnsupportedError. Guardsigtermwithif (!Platform.isWindows). - Echo & Line Mode Teardown: If setting
stdin.echoMode = falseorstdin.lineMode = false, checkif (!stdin.hasTerminal) return;first, and install aSIGINTlistener andfinallyblock to restore them so user keystrokes remain visible after exit. - Cursor Visibility: If emitting ANSI hide-cursor (
\x1B[?25l), always restore cursor visibility (\x1B[?25h) on exit or cancellation. - Socket Cleanup: Explicitly close listening
HttpServerorServerSocketinstances (server.close(force: true)) on termination signals to immediately release OS ports. - See detailed patterns in references/signals_and_terminal.md.
8. Testing CLI Applications
Structure testing across two distinct layers:
- Unit Tests (In-Memory,
< 5ms): Test command classes, option parsing, and business logic directly by importingpackage:<pkg>/src/...intest/. - Integration Tests (Subprocesses): Use
package:test_processandpackage:test_descriptorto verify end-to-end binary execution, process I/O streaming, and OS exit codes:
import 'package:test/test.dart';
import 'package:test_descriptor/test_descriptor.dart' as d;
import 'package:test_process/test_process.dart';
void main() {
test('CLI processes input and exits cleanly', () async {
await d.file('input.txt', 'hello').create();
final process = await TestProcess.start('dart', [
'run',
'bin/my_cli.dart',
'--input',
d.path('input.txt'),
]);
await expectLater(process.stdout, emitsThrough('Processing complete.'));
await process.shouldExit(0);
});
}
9. Modern Compilation & Distribution
Dart 3.12+ standardizes CLI distribution around dart run and dart install (moving away from dart pub global activate):
- Ephemeral Execution (JIT):
dart run <package>@<version> [args]downloads and runs the CLI on demand. - Global Installation (Native AOT):
dart install <package>compiles the package entrypoint to a fast native standalone binary in~/.dart/install/bin/. - Local Development: Use
dart run <command>(resolves viaexecutables:inpubspec.yaml) ordart run bin/cli.dart. - Bundling Dynamic Libraries & Code Assets: Use
dart build cli. Outputs bundle tobuild/cli/_/bundle/. - Standalone Executable Compilation: Use
dart compile exe bin/cli.dart -o <output_path>.
10. Workflows & Audit Checklist
Implementation Workflow
- Declare entry points in
pubspec.yamlunderexecutables:. - Keep
bin/*.dartas a thin entrypoint; place command logic inlib/src/. - Return integer exit codes or set
exitCode = N; avoid rawexit(N). - Direct errors, warnings, and usage on parse failure to
stderr. - Use
results.flag(),results.option(), andresults.multiOption()for type safety. - Validate
useAnsi(checkingstdout.hasTerminal,supportsAnsiEscapes, andNO_COLOR) before emitting ANSI codes. - Spawn child tools using
cli_util.dartExecutable, neverPlatform.resolvedExecutable. - Unit-test command runners in-memory; test end-to-end binary execution with
test_process.
References & Examples
- Single-Command Tool Template: examples/single_command_tool.dart
- Multi-Command Runner Template: examples/multi_command_runner.dart
- AOT SDK Discovery & Subprocess Spawning: references/aot_sdk_discovery.md
- Signal Handling & Terminal Teardown: references/signals_and_terminal.md
FAQ
What does the dart-build-cli-app skill do?
Architectural patterns, entrypoint structure, exit codes, stream routing, and subprocess spawning for Dart command-line interface (CLI) applications. Use when building CLI tools, console utilities, scripts, argument parsing with package:args (ArgParser or CommandRunner), handling exit codes, configuring executables in pubspec.yaml, spawning Dart subprocesses, or compiling native CLI binaries. Don't use for Flutter UI widgets, web applications, or standalone HTTP backend servers.
How do I install dart-build-cli-app?
Run npx skills add https://github.com/flutter/agent-plugins --skill dart-build-cli-app in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/dart-build-cli-app/ (personal) or .claude/skills/dart-build-cli-app/ (project).
Which AI agents can use dart-build-cli-app?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is dart-build-cli-app safe to install?
Security partners have reviewed it: Gen Agent Trust Hub passed; Socket passed; Snyk passed. As with any skill, read the SKILL.md and bundled scripts before installing.
Who maintains dart-build-cli-app?
It is published by flutter in flutter/agent-plugins. It has 14,231 recorded installs.
More from flutter/agent-plugins
flutter-apply-architecture-best-practices
flutter/agent-plugins
Architects a Flutter application using the recommended layered approach (UI, Logic, Data). Use when structuring a new project or refactoring for scalability.
flutter-build-responsive-layout
flutter/agent-plugins
Use LayoutBuilder, MediaQuery, or Expanded/Flexible to create a layout that adapts to different screen sizes. Use when you need the UI to look good on both mobile and tablet/desktop form factors.
flutter-fix-layout-issues
flutter/agent-plugins
Fixes Flutter layout errors (overflows, unbounded constraints) using Dart and Flutter MCP tools. Use when addressing "RenderFlex overflowed", "Vertical viewport was given unbounded height", or similar layout issues.
flutter-add-widget-test
flutter/agent-plugins
Implement a component-level test using WidgetTester to verify UI rendering and user interactions (tapping, scrolling, entering text). Use when validating that a specific widget displays correct data and responds to events as expected.
flutter-add-integration-test
flutter/agent-plugins
Configures Flutter Driver for app interaction and converts MCP actions into permanent integration tests. Use when adding integration testing to a project, exploring UI components via MCP, or automating user flows with the integrationtest package.
flutter-setup-declarative-routing
flutter/agent-plugins
Configure MaterialApp.router using a package like gorouter for advanced URL-based navigation. Use when developing web applications or mobile apps that require specific deep linking and browser history support.
Popular mobile skills
design-mobile-apps
designed-by-ai/skills
Design mobile app screens with Sleek, edit Sleek projects, and implement their designs in React Native or HTML.
ios-design
uizze.sh
Design and review iOS UI/UX for iPhone apps in SwiftUI, UIKit, or React Native. Use for mobile app design, screen redesigns, navigation flows, typography, forms, keyboard and safe-area layout, and accessibility checks. Apply Apple Human Interface Guidelines and consult real product references through the optional Uizze connection.
vercel-react-native-skills
vercel-labs/agent-skills
React Native and Expo best practices for building performant mobile apps. Use when building React Native components, optimizing list performance, implementing animations, or working with native modules. Triggers on tasks involving React Native, Expo, mobile performance, or native platform APIs.
animate-expo
emilkowalski/skills
Build animations in React Native and Expo, making the decisions in the order that determines whether they feel right — should it animate, which thread it runs on, which properties, spring or timing, how the gesture hands off, how it degrades. Writes the implementation with Reanimated, Gesture Handler, Expo Router and expo-haptics. Use when animating anything in an Expo app, adding gestures, sheets, screen transitions, press feedback or haptics, or fixing motion that stutters on device. For web animation use animate.
xcode-project-setup
firebase/agent-skills
Safely modifies Xcode projects (.pbxproj) to add Swift Packages and link files. Use this skill whenever an iOS project needs dependencies installed (e.g. Firebase, Alamofire).
firebase-remote-config-basics
firebase/agent-skills
Manages Firebase Remote Config templates, feature flags, loading strategies, and SDKs (Android, iOS). Use when downloading/deploying remoteconfig JSON templates, managing version history/feature flags, setting in-app defaults, fetchAndActivate(), real-time listeners, or SDK setup. Don't use for Firebase Hosting, Auth, Firestore, Data Connect, Crashlytics, or App Hosting.