Command Line Flags in Dart

Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag.

Dart provides an args package supporting basic command-line argument parsing. We’ll use this package to implement our example command-line program.

import 'package:args/args.dart';

void main(List<String> arguments) {
  // Create an ArgParser instance
  final parser = ArgParser();

  // Basic flag declarations are available for string,
  // integer, and boolean options. Here we declare a
  // string flag 'word' with a default value "foo"
  // and a help description.
  parser.addOption('word', defaultsTo: 'foo', help: 'a string');

  // This declares 'numb' and 'fork' flags, using a
  // similar approach to the 'word' flag.
  parser.addOption('numb', defaultsTo: '42', help: 'an int');
  parser.addFlag('fork', defaultsTo: false, help: 'a bool');

  // It's also possible to declare an option that uses an
  // existing var declared elsewhere in the program.
  var svar = 'bar';
  parser.addOption('svar', defaultsTo: svar, help: 'a string var');

  // Parse the command-line arguments
  final results = parser.parse(arguments);

  // Here we'll just dump out the parsed options and
  // any trailing positional arguments.
  print('word: ${results['word']}');
  print('numb: ${results['numb']}');
  print('fork: ${results['fork']}');
  print('svar: ${results['svar']}');
  print('rest: ${results.rest}');
}

To experiment with the command-line flags program, you need to run it using the Dart VM:

$ dart command_line_flags.dart --word=opt --numb=7 --fork --svar=flag
word: opt
numb: 7
fork: true
svar: flag
rest: []

Note that if you omit flags, they automatically take their default values:

$ dart command_line_flags.dart --word=opt
word: opt
numb: 42
fork: false
svar: bar
rest: []

Trailing positional arguments can be provided after any flags:

$ dart command_line_flags.dart --word=opt a1 a2 a3
word: opt
...
rest: [a1, a2, a3]

Use --help flag to get automatically generated help text for the command-line program:

$ dart command_line_flags.dart --help
-h, --help    Print this usage information.
    --word    a string
              (defaults to "foo")
    --numb    an int
              (defaults to "42")
    --[no-]fork    a bool
    --svar    a string var
              (defaults to "bar")

If you provide a flag that wasn’t specified to the ArgParser, the program will print an error message:

$ dart command_line_flags.dart --wat
Could not find an option named "wat".

This example demonstrates how to use command-line flags in Dart, which is similar in concept to the Go example but uses Dart-specific syntax and the args package for parsing command-line arguments.