Category Archives: Dart

Publishing Dart packages to pub.dev

Dart packages can be published to pub.dev and it’s a pretty simple process.

  • 1. Sign up to create an account on pub.dev
  • 2. Don’t worry about the Publisher, you can create and upload packages without this

Next up, let’s assume you don’t yet have a package yet – check out Creating packages to learn about the expected project layout of folders/files. We can simply run the following Dart command to create the template for us

dart create -t package-simple mypackage

Obviously change the mypackage name to that of your package.

Before we look into the requirements for publishing, let’s just state that pub.dev (when you publish your package) runs some analysis across your package and assigns you PUB POINTS – for example to follow Dart file conventions you’re expected to supply a valid pubspec.yaml, a valid README.md and a valid CHANGELOG.md.

  • Update the pubspec.yaml description field – ensure it has 60-180 characters
  • The package created by the Dart CLI gives a good starting point for the README.md and CHANGELOG.md – don’t forget to update the CHANGELOG.md to match each version
  • Implement your code in the lib/src folder – files should use lowercase, snakecase, or you’ll lose PUB POINTS
  • Ensure you’re lib .dart file has
    library mypackage;
    

    Replacing mypackage with your package name if you change the package name at any point during development.

  • Add your tests to the test folder
  • Add an example to the example folder
  • Ensure your code has doc comments to your lib .dart file as well as to the lib/src files, i.e.
    /// My Doc Comments
    

Assuming you’ve got everything in place, run

dart format .

to adhere to Dart formatting preferences. You’ll lose PUB POINTS if you publish with format issues.

Ensure your tests all run successfully using

dart test

Run the publish process in dry-run mode using

dart pub publish --dry-run

When ready, run

dart pub publish

You can exclude files from publishing by prefixing the filenames with a ., any directory with the name packages is ignored. Finally, files and directories within .pubignore or .gitignore are also excluded.

If I recall when publishing, you may be asked to log into pub.dev – just follow the publish command’s prompts and if all went well you’ll have the package upload to pub.dev.

Remember, once you’ve published a package it cannot be deleted, but you can mark them as discontinued. So make sure you have your package named as your want it to be (at the very least) before you publish it.

Ensure versions are correct and updated each time you publish, along with CHANGELOG.md updates to show what happened for each new version.

Finally pub.dev will run it’s analyse process and then supply a PUB POINT score out of 130 and will give information on what’s missing or needs attention to get a 130/130 score – for example, my current package needs a couple of files formatting correctly and an example as I didn’t use the package template but wrote mine from scratch.

Lastly, try to get your README.md etc. right before publishing as you’ll have to increment the version of your app just to change the README.md (yes I learned the hard way).

Dart web server

I know, when you think Dart you possibly think Flutter, i.e. mobile UI. However Dart is not limited to mobile. Let’s create a simple webserver using shelf 1.2.0.

First off, create a folder for our code and in there create a file with the name pubspec.yaml. This is used to store our dependencies. In this file we have the following

name: server

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  shelf: ^1.2.0
  shelf_router: ^1.0.0
  shelf_static: ^1.0.0

The ‘name’ is the name of your app – I am not being very inspiring calling mine server.

Now we’ll just copy and paste the example from Shelf. So create a file named server.dart (the name doesn’t matter, again, I was uninspiring in my choice).

So server.dart should contain the following (I’ve changed from localhost to 0.0.0.0 to access the site from another computer as this code is hosted on a headless server).

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;

void main() async {
  var handler =
      const Pipeline().addMiddleware(logRequests()).addHandler(_echoRequest);

  var server = await shelf_io.serve(handler, '0.0.0.0', 8080);

  // Enable content compression
  server.autoCompress = true;

  print('Serving at http://${server.address.host}:${server.port}');
}

Response _echoRequest(Request request) =>
    Response.ok('Request for "${request.url}"');

Next we’ll want to update/get the packages, so run

dart pub get

Finally let’s run the server using

dart server.dart

If all went well a server is run up on port 8080 and accessible via your preferred web browser. This simple example can be accessed using the following (for example)

http://192.168.1.1:8080/hello

hello is just used to get a response from the server, which will look like this Request for “hello”.

Routing

The above gives us a baseline to work from. We’re going to want to route requests to alternate functions, currently requests simple go to the _echoRequest function.

We’ve actually already added the shelf_router to our pubspec, so just import the package and add the Router. We’re going to removing the handler and the _echoRequest function, so our main function looks like this now

import 'package:shelf_router/shelf_router.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;

void main() async {

  var app = Router();

  app.get('/hello', (Request request) {
    return Response.ok('hello-world');
  });

  app.get('/user/<user>', (Request request, String user) {
    return Response.ok('hello $user');
  });

  var server = await shelf_io.serve(app, '0.0.0.0', 8080);

  server.autoCompress = true;

  print('Serving at http://${server.address.host}:${server.port}');
}

Note: This code is basically a copy of the example on shelf_router.

Installing Dart on Ubuntu 20.x

Details to install Dart on Ubuntu are listed on get-dart. I’m recreating here solely for my own reference.

sudo apt-get update
sudo apt-get install apt-transport-https
wget -qO- https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo gpg --dearmor -o /usr/share/keyrings/dart.gpg
echo 'deb [signed-by=/usr/share/keyrings/dart.gpg arch=amd64] https://storage.googleapis.com/download.dartlang.org/linux/debian stable main' | sudo tee /etc/apt/sources.list.d/dart_stable.list

Next install the Dart DSK

sudo apt-get update
sudo apt-get install dart

Export the path

export PATH="$PATH:/usr/lib/dart/bin"

Then add the PATH to your ~/.profile or ~/.bashrc, for example

echo 'export PATH="$PATH:/usr/lib/dart/bin"' >> ~/.profile

Now let’s see if it all worked, run

dart --version

If all went well you’ll see something like Dart SDK version: 2.16.1 (stable) (Unknown timestamp) on “linux_x64”.