Command Line Arguments

A CLI app is only so useful, unless you can pass arguments to your app.

Use dcli create --template=full myproject to create an example cli app that demonstrates best practices when parsing arguments.

Like many languages Dart allows you to pass arguments to your main method..

void main(List<String> args)
{
    print('Found ${arg.length} arguments.');

    print('The arguments are:');

    for (int i = 0; i < args.lenght; i++) {
        print('arg[$i]=${args[i]}');
    }
}

If you DCli script is called test.dart:

dart test.dart one two three
> Found 3 arguments.
> The arguments are:
> arg[0] = one
> arg[1] = two
> arg[2] = three

You can also stop your app and return an exit code using the exit method.

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:

To use the above application:

Last updated

Was this helpful?