runCommand method

Future<T?> runCommand(
  1. ArgResults topLevelResults

Runs the command specified by topLevelResults.

This is notionally a protected method. It may be overridden or called from subclasses, but it shouldn't be called externally.

It's useful to override this to handle global flags and/or wrap the entire command in a block. For example, you might handle the --verbose flag here to enable verbose logging before running the command.

This returns the return value of


Future<T?> runCommand(ArgResults topLevelResults) async {
  var argResults = topLevelResults;
  var commands = _commands;
  Command? command;
  var commandString = executableName;

  while (commands.isNotEmpty) {
    if (argResults.command == null) {
      if ( {
        if (command == null) {
          // No top-level command was chosen.
          return null;

        command.usageException('Missing subcommand for "$commandString".');
      } else {
        var requested =[0];

        // Build up a help message containing similar commands, if found.
        var similarCommands =
            _similarCommandsText(requested, commands.values);

        if (command == null) {
              'Could not find a command named "$requested".$similarCommands');

        command.usageException('Could not find a subcommand named '
            '"$requested" for "$commandString".$similarCommands');

    // Step into the command.
    argResults = argResults.command!;
    command = commands[]!;
    command._globalResults = topLevelResults;
    command._argResults = argResults;
    commands = command._subcommands as Map<String, Command<T>>;
    commandString += ' ${}';

    if (argResults.options.contains('help') && (argResults['help'] as bool)) {
      return null;

  if (topLevelResults['help'] as bool) {
    return null;

  // Make sure there aren't unexpected arguments.
  if (!command!.takesArguments && {
        'Command "${}" does not take any arguments.');

  return (await as T?;