Command Line Arguments in Dart

Here’s the translated Dart code and explanation in Markdown format suitable for Hugo:

Command-line arguments are a common way to parameterize execution of programs. For example, dart run hello.dart uses run and hello.dart arguments to the dart command.

import 'dart:io';

void main(List<String> arguments) {
  // arguments provides access to raw command-line arguments.
  // Note that unlike some other languages, Dart doesn't include
  // the program name as the first argument.
  List<String> argsWithProg = [Platform.executable, ...arguments];
  List<String> argsWithoutProg = arguments;

  // You can get individual args with normal indexing.
  String arg = arguments.length > 2 ? arguments[2] : '';

  print(argsWithProg);
  print(argsWithoutProg);
  print(arg);
}

To experiment with command-line arguments it’s best to run the Dart script directly.

$ dart run command_line_arguments.dart a b c d
[/path/to/dart, a, b, c, d]
[a, b, c, d]
c

In Dart, the main function can optionally take a List<String> parameter which contains the command-line arguments. The Platform.executable property is used to get the path to the Dart executable, which we include to mimic the behavior of languages that include the program name as the first argument.

The dart:io library is imported to use the Platform class, which provides information about the environment in which the program is running.

Next, we’ll look at more advanced command-line processing with option parsing libraries available in Dart.