Search…
Command Line Arguments
A CLI app is only so useful unless you can pass arguments to your app.
Like many languages Dart allows you to pass arguments to your main method..
1
void main(List<String> args)
2
{
3
print('Found ${arg.length} arguments.');
4
5
print('The arguments are:');
6
7
for (int i = 0; i < args.lenght; i++) {
8
print('arg[$i]=${args[i]}');
9
}
10
}
Copied!
If you DCli script is called test.dart:
1
dart test.dart one two three
2
> Found 3 arguments.
3
> The arguments are:
4
> arg[0] = one
5
> arg[1] = two
6
> arg[2] = three
Copied!
You can also stop your app and return an exit code using the exit method.
1
import 'dart:io';
2
3
void main(List<String> args)
4
{
5
print('Found ${arg.length} arguments.');
6
7
/// stops the progam so no further lines will be executed.
8
/// The progam outputs an exit code of 1.
9
exit(1);
10
11
print('The arguments are:');
12
13
for (int i = 0; i < args.lenght; i++) {
14
print('arg[$i]=${args[i]}');
15
}
16
}
Copied!

ArgParser

For simple command argument processing you can process the args argument yourself.
If you want to do more complex argument processing then its better to get some help.
The Dart team has very kindly put together the args package which provides advanced argument parsing. The DCli API includes the args package so you do NOT need to add it to your pubspec.yaml dependencies.
You can read all about using the args package on pub.dev but here is a little example of what you can do:
1
import 'dart:io';
2
import 'package:dcli/dcli.dart';
3
4
/// This is a full implementation of the linux cli 'which' app.
5
/// The which command searches the PATH for the passed exe.
6
void main(List<String> args) {
7
8
/// create the parser and add a --verbose option
9
var parser = ArgParser();
10
parser..addFlag('verbose', abbr: 'v', defaultsTo: false, negatable: false);
11
12
/// parse the passed in command line arguments.
13
var results = parser.parse(args);
14
15
/// get the value of the passed in verbose flag.
16
var verbose = results['verbose'] as bool;
17
18
/// The 'rest' of the results are any additional arguments
19
/// we only expect one which is the name of the exe we are looking for.
20
if (results.rest.length != 1) {
21
print(red('You must pass the name of the executable to search for.'));
22
print(green('Usage:'));
23
print(green(' which ${parser.usage}<exe>'));
24
exit(1);
25
}
26
27
/// name of the command we will search for.
28
var command = results.rest[0];
29
var home = env['HOME'];
30
31
List<String> paths = Env().path;
32
33
for (var path in paths) {
34
if (path.startsWith('~')) {
35
path = path.replaceAll('~', home);
36
}
37
if (verbose) {
38
print('Searching: ${canonicalize(path)}');
39
}
40
if (exists(join(path, command))) {
41
print(red('Found at: ${canonicalize(join(path, command))}'));
42
}
43
}
44
}
Copied!
To use the above application:
1
dart which.dart ls
2
Found at: /usr/bin/ls
3
Found at: /bin/ls
Copied!
Last modified 1mo ago
Copy link
Contents
ArgParser