Officialflutter/agent-plugins5 files

Dart Build CLI App

>-

Specification
Skill ID
flutter/agent-plugins/dart-build-cli-app
Publisher
flutter
Repository
agent-plugins
Installs
131
Files
5
Synced
Sep 16, 2026
How to use it

Open any RiverX project, open the Skills panel in the chat, and search for this identifier. The files are fetched from the source repository at install time.

flutter/agent-plugins/dart-build-cli-appInstalls these files
  • SKILL.md
  • examples/multi_command_runner.dart
  • examples/single_command_tool.dart
  • references/aot_sdk_discovery.md
  • references/signals_and_terminal.md

What this skill tells the agent

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:coverage queries execution lines over VM Service RPCs during the paused-on-exit state. exit() destroys the process before RPC extraction, yielding 0% coverage.
  • Buffer Truncation: stdout and stderr are buffered asynchronous IOSink streams. exit() drops unflushed bytes.
  • Resource Leaks: finally blocks (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 via package: URIs. Moving logic into lib/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 to stderr.
  • The Error Usage Rule: When an argument parsing or mandatory option error occurs (FormatException, UsageException, or ArgumentError thrown when accessing a missing mandatory: true option via results.option(...)), both the error message and the usage text must write to `stderr`, and exit code 64 (EX_USAGE / ExitCode.usage.code) must be returned. stdout should ONLY receive usage help when the user explicitly requests it via --help or -h.
  • No `print()` in Error Handlers: print() routes to stdout. Use stderr.writeln() for all failure notifications. For standard output, prefer stdout.writeln() over print() to comply with the `avoid_print` lint rule (unless analysis_options.yaml explicitly configures avoid_print: false).
  • Terminal Capability Detection & `NO_COLOR`: Verify stdout.hasTerminal, stdout.supportsAnsiEscapes, and !Platform.environment.containsKey('NO_COLOR') before emitting ANSI color or cursor escape codes: ``dart bool get useAnsi => stdout.hasTerminal && stdout.supportsAnsiEscapes && !Platform.environment.containsKey('NO_COLOR'); ``
  • Machine-Readable Modes: When --json or --machine flags are passed, format data as JSON to stdout and route logs to stderr.

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 ArgParser directly with addFlag() and addOption().
  • Multi-Command Tools: Implement CommandRunner<int> and extend Command<int> for each subcommand, returning POSIX exit codes directly.
  • Type-Safe Accessors: Use results.flag('name'), results.option('name'), and results.multiOption('name') (available in package:args 2.5+) instead of map indexing operator [] to eliminate manual type casts (as bool, as String?).
  • Complex Options Models: For applications with extensive flags, use package:build_cli to 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 across await suspension points. Chain.capture wraps the event loop in custom Zones, incurring substantial allocation overhead and trapping errors across Zone boundaries.