This tutorial explains about How to create a package in Dart and Flutter, Publish to dart.pub Following are steps to required a package

  • Create a package project in Dart
  • Package Folder Structure
  • Adding Reusable a code in Package
  • Test the package with an example
  • Run the example
  • Adding & Running test cases
  • Generating Documentation
  • License file
  • publish package
  • import package in other applications to use

Create a package project in Dart

Open terminal, Run the below command

dart create -t package stringutils
  • dart create command used to create a scalfolding folder structure, with required files.
  • -t is an alias for --template option, with value package it creates a package with value package.
  • stringutils is a package name to create
PS E:\myblogs> dart create -t package stringutils
Creating stringutils using template package...

  .gitignore
  analysis_options.yaml
  CHANGELOG.md
  pubspec.yaml
  README.md
  example\stringutils_example.dart
  lib\stringutils.dart
  lib\src\stringutils_base.dart
  test\stringutils_test.dart

Running pub get...
  Resolving dependencies...
  Changed 47 dependencies!
  2 packages have newer versions incompatible with dependency constraints.
  Try `dart pub outdated` for more information.

Created project stringutils in stringutils! In order to get started, run the following commands:

  cd stringutils
  dart run example/stringutils_example.dart

It creates an stringutils folder that contains all required files to create package.

Folder Structure of Dart package

The folder structure of Dart package is as follows

ª   .gitignore
ª   analysis_options.yaml
ª   CHANGELOG.md
ª   pubspec.lock
ª   pubspec.yaml
ª   README.md
ª   tree.txt
ª
+---.dart_tool
ª       package_config.json
ª
+---example
ª       stringutils_example.dart
ª
+---lib
ª   ª   stringutils.dart
ª   ª
ª   +---src
ª           stringutils_base.dart
ª
+---test
        stringutils_test.dart

  • .gitignore: text file contains path of files/folders to ignore for pushing changes to Git
  • analysis_options.yaml: Contains code rules to do lint check for errors, warnings, suggestions.
  • CHANGELOG.md: CHANGELOG markdown file, contains changes for a package
  • README.md: README markdown file, contains readme instructions for a package users, how to use, how to contribute, and more.
  • pubspec.yaml: YAML file contains package Meta information such as name, version, dependencies and dev_dependencies
  • example folder: Contains example usage of packages with examples
  • lib folder: Contains code for package
  • lib\src folder: Contains code for package
  • test folder: Test cases for package

Adding Reusable a code in Package

Go to stringutils_base.dart in lib/src folder. Added a two methods

  • toUpperString() convert String to upper case
  • toLowerString() converts String to lower case

Triple slashes(///) are documentation comments syntax used to write a develper comments.

lib/src/stringutils_base.dart

// TODO: Put public facing types in this file.

/// String utility function.
class StringUtils {
  /// The toUpperString funtion converts string to lowercase
  String toUpperString(String str) {
    return str.toUpperCase();
  }

  /// The toLowerString funtion converts string to lowercase
  String toLowerString(String str) {
    return str.toLowerCase();
  }
}

Exported these two methods in stringutils.dart, It can be used by all classes in the library.

/// Support for doing something awesome.
///
/// More dartdocs go here.
library;


// TODO: Export any libraries intended for clients of this package.
export 'src/stringutils_base.dart';

Running the example code

Example in library helps developer to test code inline during development. It also helps developer for usage of methods of package.

Create stringutils.dart class in examples folder.

import 'package:stringutils/stringutils.dart';

void main() {
  var utils = StringUtils();
  var str = "Welcome test";
  print(utils.toUpperString(str)); // WELCOME TEST
  print(utils.toLowerString(str)); // welcome test TEST
}

open terminal, run dart run code example

PS E:\myblogs\stringutils> dart run example/stringutils_example.dart
WELCOME TEST
welcome test

Adding test cases

You can write unit and integration test cases in a test folder.

test folder contains code for test cases, executed during test run.

create a stringutils_test.dart, updated with test cases.

  • group() method used to define group of tests
  • setUp(): Setup code initialization, calls for every test case execution
  • test() method , to create single indivial test cases.

In this example, Create a StringUtils object, inside a group function. Added test cases for each method of stringutils, Call methods, asset the return value with actual value using expect call

import 'package:stringutils/stringutils.dart';
import 'package:test/test.dart';

void main() {
  group('String Utils tests', () {
    final utils = StringUtils();

    setUp(() {});

    test('toLowerString Test', () {
      expect(utils.toLowerString("JOHN"), "john");
    });
    test('toUpperString Test', () {
      expect(utils.toUpperString("john"), "JOHN");
    });
  });
}

Once test cases are done, You need to run dart test command in the terminal

PS E:\myblogs\stringutils> dart test
Building package executable... (21.9s)
Built test:test.
00:02 +2: All tests passed!

Generating Documentation

Documentation helps developer to understand the package in more depth.

/// String utility function.
class StringUtils {

  /// The toUpperString funtion converts string to lowercase
  ///
  /// Example:
  /// ```dart
  /// final utils = StringUtils();
  /// print(utils.toUpperString("hello")); // Output: HELLO
  /// ```
  String toUpperString(String str) {
    return str.toUpperCase();
  }

  /// The toLowerString funtion converts string to lowercase
  ///
  /// Example:
  /// ```dart
  /// final utils = StringUtils();
  /// print(utils.toLowerString("HELLO")); // Output: hello
  /// ```
  String toLowerString(String str) {
    return str.toLowerCase();
  }
}

Next, Generate Documentation using dart doc command in terminal

PS E:\myblogs\stringutils> dart doc .
Documenting stringutils...
Initialized dartdoc with 46 libraries
Generating docs for library stringutils from package:stringutils/stringutils.dart...
no issues found
Documented 1 public library in 40.7 seconds
Success! Docs generated into e:\myblogs\stringutils\doc\api

It Generates a doc/api folder in a project.

Add LICENSE file to a project

To publish a packages in dart, Must declare an LICENSE file in a project.

LICENSE is an test file that contains statements about usage of code for open source usage.

Open LICENSE file in a project and add license statement in it.

Publish package to pub.dev

First, dart.dev to verify as an publisher

dart pub login

It gives url, Open URL, give access, once done, you are able to authorize it.

PS E:\myblogs\stringutils> dart pub login
Pub needs your authorization to upload packages on your behalf.
In a web browser, go to url
Then click "Allow access".

Waiting for your authorization...
Authorization received, processing...
Successfully authorized.
You are now logged in as <[email protected]>

Next, run dart pub publish --dry-run to validation dry run check on guidelines & layout conventions, required missing files, upload to repository.

Next, type dart pub publish command to publish to dart.dev

Your stringutils package is avialble in dart.dev to use it

How to import the package in other applications

In your project, add dependency in pubspec.yaml with below package information.

dependencies:
  stringutils: ^1.0.0

Next, run dart pub get to install package to a project.

In the code, Import library into a code.

test.dart

void main() {
  var utils = StringUtils();
  var str = "Welcome test";
  print(utils.toUpperString(str)); // WELCOME TEST
  print(utils.toLowerString(str)); // welcome test TEST
}

Conclusion

You have successfully created a package in Dart with the help of Dart CLI.