Create a command line app with dart

Marvin Knabe
5 min readMay 15, 2019

--

Dart is a great ‘new’ programming language. I really love it to use with Flutter, I never tried it with Angular, but I know developers who have done this and they said me the same. But we can use Dart 🎯 for building command line apps too. So let’s try it 🤤

What do we want to build ?

A little command line tool, that calls the OpenWeatherAPI, we set some parameters like the zip code and the country and this is our output:

Simple and great to understand the fundamentals. So let’s start.

First we have to install something, yes okay we need Dart 😃 and here is the link for the install instructions -> https://dart.dev/get-dart

In the next step we want to install stagehand with this command:
pub global activate stagehand
Stagehand is a little Dart Project Generator for command line apps, web servers and so on.

So after that let’s create a folder 📁 somewhere and generate a little starter project.

mkdir dartweather && cd dartweather && stagehand console-full

After that you can see, we have some new Folders, a main.dart and a dartweather.dart file, pubspec and so on. Great. 👍 Now let’s run pub get and we can start.

Okay here you see mediumtest.dart… shame on me

I like it more to start from scratch, so I deleted everything inside the main.dart and dartweather.dart .

Inside your main.dart add this code, I will explain it.

I think the imports should be clear. Args for arguments, dart io for io things, and our app logic from the dartweather file. Nothing special.
So the main method is our entry point, like in every other dart application.
In the first line we are setting the exitCode to 0. It says, that everything is fine here and we can go on. There are 3 exitcode options.

0 = Success
1 = Warnings
2 = Errors

After that we are creating an Argumentparser. We can define out options, inputs and so on there.

The addOption method needs a name value, like zip . When we want to run our application, we can call it like this dartweather --zip 1234 . To make a short option, we set the abbr attribute. There are many other options, like a help text and so one. Have a look on it.
For the country option, we set a default value. So I’m living in germany, thats why I took de . Choose what you want.

Then we are parsing our input with final argResults = parser.parse(arguments);

This creates a map with String-Keys and our choosen values. Thats why we added the names to our options.

Now we can run our logics.

So what do we really want to do ? We call the Api (go to https://openweathermap.org/api and create an account for your api key) and show some weather informations.

So let us begin with the basic stuff. We need some Models.

I took the example Json and converted it to Dart with this Website: https://javiercbk.github.io/json_to_dart/

But beware of some things here, sometimes this converter doesn’t recognize double values correctly. I refactored the most int values to a double value, some renamings etc.

So this is the result:

Okay okay, maybe we should split this in smaller files… feel free to do that 😃

Now let’s add a constant file, for our API Key 🔑 , base url etc.

And for some fun, I created a runes file, so we can add Emojis to our console output! EMOJIIIS! Everyone loves that right?

After all this things, create a file, called api.dart . There we want to create a method, that returns a Future<ForeCast> with two parameters.

So this is very basic, we create an url, get the response, decode the data to json and convert it to our model.

So now we have done the most things, the last part is to create a correct console output and calling our method.

First we check our parameters, if everything is okay, we call our api method and wrap it with try & catch. With stdout.writeln() we write a new line, stderr.writeln() tells the console, that this is an error, after that the applicaton will be closed.

So now we can test our hacky command line tool.

So open your terminal inside your development folder and type
dart bin/main.dart -z #YOURZIPCODE#

You should the following output:

Maybe it loads a little bit longer, thats because we don’t really compiled it to super fast machine code. So lets do this now.

dart2aot bin/main.dart bin/main.dart.aot
dartaotruntime bin/main.dart.aot

So now you see, it’s super fast. 💨 You can measure it with this command.

time dartaotruntime bin/main.dart.aot

But one ☝️ thing is missing. I don’t want to call it with the path and dartaotruntime. I want a quick and little command, overall inside my console. So let’s do this last part.

Go to you pubspec.yaml and add this property at the end.

There we can define the name of our command line tool and the entry point.
After that, we make it global.

pub global activate --source path <path to project in my case ~/develop/dartweather>

Great! Now we can call our app, everywhere inside our terminal.
Thank you for reading!

If you can’t call the global value, you have to add the PATH to you .bash_profile | .bashrc maybe.

export PATH="$PATH":”HOME/.pub-cache/bin"

--

--