P E N C I L
Login
Tutorial: Write a Dart library package

Introduction

This tutorial shows you

- How to create a simple Dart library package

- Run unit test

- Publish on Pub site

Requirements

- Dart env is setup
Ref. https://www.dartlang.org/install

Quick start

A Dart package contains multiple files.

The quickest way to start is to generate a sample dart package and then modify it.

You can clone from sample package

https://github.com/golery/sample-dart-package

If you are using Intellij Dart plugin, you can generate a sample project: File > New Project.
Choose Dart > Dart Package sample content.

Dart package basics

Package vs library

A dart package can contain several library.

How to use a package

In order to use a package, first add the package as a dependency in pubsec.yaml

dependencies:
  mypackage: ^1.0.0

Then in source code, import the library in the package

import 'package:<packagename>/<libraryname>.dart';

Dart package file structures

The folder structure is organized as below.

Folder example

contains example dart file which shows how to use the library

Folder lib

contains implementations of libraries

In this example, there are 2 library lib1 and lib2.

Lib1.dart exports class Adder

library lib1;

export 'src/adder.dart';

lib2.dart exports constants in constants.dart

library lib2;

export 'src/constants.dart';

Folder test

contains unit test of libraries

File test.dart

import 'package:sample_package/lib1.dart';
import 'package:test/test.dart';

void main() {
  group('Group1:', () {
    test('Test Adder.add()', () {
      expect(Adder().add(1,2), 3);
    });
  });
}

Run test

In order to run unit test, run

pub run .\test\test.dart

Publish

Now it's time to publish. Just run

pub publish

You will see message

Looks great! Are you ready to upload your package (y/n)? y

Pub needs your authorization to upload packages on your behalf.

In a web browser, go to https://accounts.google.com/o/oauth2/auth?.....
Then click "Allow access".

Copy the url in the browser, login and then it's done !

References

1. https://www.dartlang.org/guides/libraries/create-library-packages