Writing your first CLI app
Let's start by going over the basics of writing the classic Hello World program.
Create a directory to work in:
mkdir dcli_scripts
cd dcli_scriptsmkdir dcli_scripts
cd dcli_scriptsmkdir dcli_scripts
cd dcli_scriptsUsing your preferred editor create a file called 'hello.dart' with following content:
void main() {
print('Hello World.');
}Running
Now let's run your script:
dart hello.dart
> Hello World.When we run our script using the dart command, Dart performs JIT compilation of our script which slows down the startup time a little but makes for fast test iteration.
Compiling
You can compile your script to a native executable so that it launches and runs much faster.
You now have a completely self-contained executable which you can copy to any binary compatible machine.
The exe is 8MB in size and does NOT require Dart to be installed.
Dependencies
So far we haven't actually used the DCli API in our hello.dart program. Let's now set up dependency management so we can use the DCli API and any other Dart package.
Dart uses a special file called pubspec.yaml to control the set of packages accessible to your application.
Dart's pubspec.yaml is equivalent to a makefile, pom.xml, gradle.build or package.json, in that it defines the set of dependencies for your application.
To use the DCli API or any other Dart package you need to add the dependency to your pubspec.yaml.
Create and edit your first 'pubspec.yaml' file using your preferred editor:
Whenever you change your 'pubspec.yaml' you must run 'dart pub get' to download the required dependencies:
Writing a DCli script
Now that we have added DCli to our pubspec.yaml we can modify hello.dart to make calls to the DCli API.
Edit your hello.dart script as follows:
Now run our script.
You are now officially a DCli guru.
Go forth young man (or gal) and create.
Last updated
Was this helpful?