CodeBlanks Logo Icon CodeBlanks

ArgParser

Learn option processing with ArgParser.

ArgParser option types

ArgParser adds options with three methods. addOption('name') is a text option; the user gives --name=value. addFlag('verbose') is a boolean flag; --verbose means true, absence means false. addMultiOption('files') is a multi-value list.

Each method takes abbr (abbreviation) and help (help text). Example: addFlag('verbose', abbr: 'v', help: 'Verbose output'). After parsing results['verbose'] returns true or false.

ArgResults

parser.parse(arguments) returns an ArgResults object. You access option values with results['name']. Flags return boolean, options return text, multi-options return lists.

Positional arguments are in the results.rest list. You check whether an option was given with results.wasParsed('name'). This is the core way to trigger different behaviors in a CLI tool. For example if the --verbose flag was given you turn on verbose output; otherwise you run silently.

Practice Parse a flag and a file

Add import 'package:args/args.dart';. In main create final parser = ArgParser()..addFlag('verbose', abbr: 'v')..addOption('file');. Parse with final results = parser.parse(['--verbose', '--file=notlar.txt']);. Print with print('Verbose: ${results['verbose']}') and print('File: ${results['file']}').

Starter code

main.dart
// import the args package

void main() {
  // parse --verbose flag and --file option with ArgParser
}

Sample solution

main.dart
import 'package:args/args.dart';

void main() {
  final parser = ArgParser()
    ..addFlag('verbose', abbr: 'v')
    ..addOption('file');
  final results = parser.parse(['--verbose', '--file=notlar.txt']);
  print('Verbose: ${results["verbose"]}');
  print('File: ${results["file"]}');
}

Expected output

Verbose: true
File: notlar.txt

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 The addFlag call

Question
parser.____('verbose', abbr: 'v');
Answer
parser.addFlag('verbose', abbr: 'v');

Explanation: addFlag('verbose', abbr: 'v') adds a boolean flag.

2 What does addFlag add?

  • List
  • Boolean flag Correct answer
  • Number
  • Text option

Explanation: addFlag adds a boolean flag.

3 Match the ArgResults parts

Term Meaning
results['name'] Option value
results['verbose'] Boolean flag
results.rest Positional args
wasParsed Was-given check

All lessons in Advanced