Thuta Learning
Dart
AdvancedProgrammingBeginner

Packages, Pub & Project Tooling

DartLesson 2430 min

What you'll walk away with

  • Read and write the main pubspec.yaml fields: name, environment, dependencies and dev_dependencies
  • Explain which versions a caret constraint such as ^1.2.3 or ^0.2.3 allows
  • Tell pubspec.yaml from pubspec.lock and decide whether to commit the lock file
  • Know what lib/, lib/src/, bin/ and test/ are for and connect them with package: imports
  • Build dart format, analyze, fix and test into a daily workflow

Explain it simply

Explain it simply

A package is a bundle of code with a name, a version and a list of what it needs. Think of a packaged food product: the label tells you what is inside, when it was made and which ingredients it requires. In Dart that label is pubspec.yaml.

Pub is Dart's package manager. It reads pubspec.yaml, fetches the packages you need from pub.dev, and records the versions it chose in pubspec.lock. The remaining tools keep your code tidy and honest: dart format lays it out, dart analyze finds problems, dart test runs your tests.

Problem → Why → Solution

The problem: copied code and unbounded dependencies

Say you copy utils.dart into three projects. You fix a bug in one, and the other two silently keep it. Then a dependency declared as any picks up a new major release a month later, and a project you never touched stops building.

Look at this pubspec too: the name contains a space and capital letters, collection is declared as any, and http has no version at all. Pub refuses that name, and the other two lines are accepted but unsafe.

pubspec.yaml
name: Task Core          # invalid: pub wants lowercase_with_underscores
dependencies:
  collection: any        # accepts every release, even breaking ones
  http:                  # no constraint written at all

What does a package system protect you from?

A package gives a piece of code a name, a version and a contract. pubspec.yaml states what you need and which version ranges you accept, and pubspec.lock records exactly which versions were chosen. That ends copy-pasting code and makes the build the same on every machine.

Core concept: write a range, lock the choice

A Dart package is a directory that contains a pubspec.yaml. Keep three files apart in your head. pubspec.yaml is the one you write and holds the ranges you want. pubspec.lock is written by pub and holds the exact versions it chose. .dart_tool/package_config.json is a generated file that maps package names to folders; you never commit it.

File or folderPurposeCommit it?
pubspec.yamlNeeds and version rangesYes
pubspec.lockThe exact versions chosenApps yes, libraries no
.dart_tool/Files generated by pub and toolsNo

Versions follow semantic versioning, major.minor.patch. ^1.2.3 means the same as >=1.2.3 <2.0.0: any 1.x release that is trusted not to break you. While the major number is 0, a minor bump counts as breaking, so ^0.2.3 means >=0.2.3 <0.3.0. Pub picks the newest versions that satisfy the constraints of your pubspec and of every dependency's pubspec at once. When two packages need incompatible versions of the same third package, resolution fails with 'version solving failed' and explains which constraints clash.

A dependency can come from three places: hosted (pub.dev by default), a path on disk, or a git repository. dependency_overrides lets you temporarily force a version you are testing, but it is meant to be short-lived, so remove it before you commit.

The layout follows conventions as well. Code in lib/ is public, while lib/src/ holds the implementation that other packages should not import directly; one file in lib/ exports the API you want the world to see. bin/ holds runnable programs, test/ holds files ending in _test.dart, and example/ holds demos. Code is imported by package name, as in package:task_core/task_core.dart.

Mental model: an order form and a receipt
  1. pubspec states the ranges you accept
  2. Pub picks versions fitting all constraints
  3. pubspec.lock records the exact picks
  4. package: imports find code by name

The range is the order form and the lock file is the receipt; the receipt only changes when you change the order or ask pub to upgrade.

General pattern

yaml
name: package_name
environment:
  sdk: ^X.Y.Z
dependencies:
  hosted_package: ^1.2.3
  local_package:
    path: ../local_package
dev_dependencies:
  test: ^1.0.0

Write name, environment.sdk, dependencies and dev_dependencies in order. Each dependency can be a caret constraint or a path or git source.

A pubspec.yaml for a task package

This pubspec describes a package called task_core, a private package holding the models that both a CLI and a server will share. It depends on one package from pub.dev and one sibling package in the same repository, and keeps its test and lint packages in dev_dependencies.

The file is configuration, so it does not run and prints nothing. As soon as you run dart pub get, pub reads it and writes pubspec.lock. The version numbers are illustrative: if you add a package with dart pub add, pub writes the right constraint for today.

pubspec.yaml
name: task_core
description: Task models and rules shared by the CLI and the server.
version: 0.3.0
publish_to: none   # private package: blocks an accidental "dart pub publish"

environment:
  sdk: ^3.8.0

dependencies:
  collection: ^1.18.0   # hosted on pub.dev
  task_storage:         # a sibling package in the same repository
    path: ../task_storage

dev_dependencies:
  lints: ^6.0.0
  test: ^1.26.0

Code breakdown

  1. The package namename: task_core

    The name must be lowercase with underscores. Other code will import it as package:task_core/..., so the name is part of your public surface.

  2. Staying privatepublish_to: none # private package: blocks an accidental "dart pub publish"

    With publish_to: none, dart pub publish refuses to upload the package. It is a good guard for internal company packages.

  3. The SDK constraintsdk: ^3.8.0

    This says the oldest Dart SDK the package supports; on an older SDK, dart pub get fails. Write the lowest version your code genuinely needs.

  4. A hosted dependencycollection: ^1.18.0 # hosted on pub.dev

    The caret constraint allows >=1.18.0 <2.0.0. Pub picks the newest release inside that range and writes it into pubspec.lock.

  5. A path dependencypath: ../task_storage

    A path dependency points straight at a folder on disk. It is common in a monorepo, where packages are developed together without being published.

  6. Development-only packagesdev_dependencies:

    test and lints matter only to the people building this package. Keeping them here means consumers of the package are not forced to install them.

A day's work on a package
  1. dart create -t package starts the package
  2. dart pub add adds a dependency
  3. Write code in lib/ and tests in test/
  4. Run format, analyze and test before commit

Resolution succeeds

pubspec.lock is written and every tool can find the packages.

Constraints clash

Pub reports 'version solving failed' and explains which ranges conflict.

Reading a version constraint

ConstraintAllowed rangeNote
^1.2.3>=1.2.3 <2.0.0The usual default
^0.2.3>=0.2.3 <0.3.0Minor is breaking at major 0
>=1.2.0 <1.5.0Exactly as writtenWhen you need a tighter bound
anyEvery versionAvoid it

You will understand the rule best by coding it. The mini challenge at the end of this lesson asks you to write a caret-constraint checker: find the lowest allowed version and the first breaking version, then test whether a version falls between them.

Layout and imports

text
A library package
-----------------
task_core/
  pubspec.yaml            what the package needs
  pubspec.lock            exact versions chosen (generated)
  analysis_options.yaml   lint rules
  lib/
    task_core.dart        public API: mostly export lines
    src/                  implementation, private by convention
  bin/                    runnable programs
  test/                   files ending in _test.dart
  example/                small runnable demos

lib/task_core.dart exports only what you want to publish from src/. That way you can reorganise or rename files inside src/ without breaking anyone's imports. These snippets need a real package around them, so they cannot run as a single file here.

lib/task_core.dart
// The public face of the package: only these names are the supported API.
export 'src/task.dart' show Task, TaskStatus;
export 'src/task_list.dart';
bin/task_cli.dart
import 'package:task_core/task_core.dart';

void main() {
  final list = TaskList();
  list.add(Task('Write README'));
  print(list.openCount);
}

Day-to-day commands

bash
dart create -t package task_core   # new library package
cd task_core
dart pub add collection            # runtime dependency
dart pub add --dev test            # development-only dependency
dart pub get                       # resolve and write pubspec.lock
dart format .                      # canonical layout
dart analyze                       # static analysis
dart fix --apply                   # apply automated fixes
dart test                          # run test/*_test.dart
dart pub outdated                  # what could be upgraded

dart analyze reads analysis_options.yaml. include: package:lints/recommended.yaml brings in the rule set the Dart team recommends, and the analyzer's strict options catch values that quietly turn into dynamic. Dart tools often fetch missing dependencies for you, but running dart pub get yourself makes the lock-file step explicit.

analysis_options.yaml
include: package:lints/recommended.yaml

analyzer:
  language:
    strict-casts: true
    strict-inference: true
    strict-raw-types: true

In real projects

In real projects

A Flutter app is also just a Dart package with a pubspec.yaml; it adds a flutter: section where assets and fonts are declared. Companies often put domain models into one package and let the mobile app, the web app and the server share it through a path or git dependency. To share a command-line tool, dart compile exe bin/tool.dart produces a native executable that runs even on machines without Dart installed.

In CI the usual steps are dart format --output=none --set-exit-if-changed ., dart analyze --fatal-infos and dart test, one after the other, and a failure blocks the merge. A package you intend to publish is checked first with dart pub publish --dry-run. Teams also look at dart pub outdated regularly and upgrade on purpose rather than by surprise.

Common mistakes

Common mistakes

Declaring a dependency as any or without a constraint

With collection: any, pub may choose a new major release that contains breaking changes, and your build fails without any change in your own code. Use a caret constraint such as ^1.18.0; dart pub add writes that form for you.

Getting the lock file policy backwards

Not committing the lock file of an application lets every developer and the CI pick different versions, which produces 'works on my machine'. Committing the lock file of a library gives false confidence: your tests run on those exact versions, while the people who use your library resolve their own. Commit it for applications, not for libraries.

Importing from another package's src/

Writing import 'package:other/src/internal.dart' reaches into code that is not other's public API. Its owner may move or rename it even in a minor release, and your code breaks. Import only the files that are exported at the top level of lib/.

Putting packages in the wrong dependency section

Putting test under dependencies forces everyone who uses your package to download it as well. The opposite mistake, importing a package from lib/ while declaring it only under dev_dependencies, breaks the people who depend on you because they never receive it. Use dependencies for what lib/ imports and dev_dependencies for what test/ and tools import.

Best practices

Best practices

  • Add dependencies with dart pub add so pub writes the constraint correctly.
  • Export the public API from lib/ and keep the implementation in lib/src/.
  • Run dart format, dart analyze and dart test before every commit and in CI.
  • Commit pubspec.lock for applications, not for libraries.

Mini challenge

Write a caret-constraint checker

Turn pub's caret rule into code: ^1.2.3 means >=1.2.3 <2.0.0 and ^0.2.3 means >=0.2.3 <0.3.0. Parse version strings, test them against a constraint and print the results. Also handle malformed input.

  • parseVersion(text) returns a (major, minor, patch) record and throws a FormatException unless there are exactly three parts
  • allows(constraint, version) accepts only constraints that start with ^ and throws a FormatException otherwise
  • When major > 0 the first breaking version is the next major; when major == 0 it is the next minor
  • main() prints five cases as '^1.2.3 allows 1.9.0: true' and catches the error for '^1.2' with try/catch
caret.dart
// A version is (major, minor, patch).
(int, int, int) parseVersion(String text) {
  // TODO: split on '.'; unless there are exactly three parts,
  //       throw FormatException('expected major.minor.patch', text)
  // TODO: int.parse each part and return the record
}

bool allows(String constraint, String version) {
  // TODO: reject anything that does not start with '^'
  // TODO: work out the lowest allowed version and the first breaking version
  // TODO: return true when lowest <= version < first breaking
}

void main() {
  // TODO: print "<constraint> allows <version>: true/false" for five cases
  // TODO: call allows('^1.2', '1.2.0') in try/catch and print the problem
}

Expected: Six lines: ^1.2.3 allows 1.9.0: true, ^1.2.3 allows 2.0.0: false, ^1.2.3 allows 1.2.2: false, ^0.2.3 allows 0.2.9: true, ^0.2.3 allows 0.3.0: false, and finally invalid: expected major.minor.patch.

Show hint

Records can be compared with == but not with <, so write a small helper that compares major, then minor, then patch with compareTo. The first field of a record is read with $1.

Show solution
caret.dart
(int, int, int) parseVersion(String text) {
  final parts = text.split('.');
  if (parts.length != 3) {
    throw FormatException('expected major.minor.patch', text);
  }
  final numbers = parts.map(int.parse).toList();
  return (numbers[0], numbers[1], numbers[2]);
}

int compare((int, int, int) a, (int, int, int) b) {
  if (a.$1 != b.$1) return a.$1.compareTo(b.$1);
  if (a.$2 != b.$2) return a.$2.compareTo(b.$2);
  return a.$3.compareTo(b.$3);
}

bool allows(String constraint, String version) {
  if (!constraint.startsWith('^')) {
    throw FormatException('only caret constraints are supported', constraint);
  }
  final base = parseVersion(constraint.substring(1));
  final candidate = parseVersion(version);
  final firstBreaking = base.$1 > 0 ? (base.$1 + 1, 0, 0) : (0, base.$2 + 1, 0);
  return compare(candidate, base) >= 0 && compare(candidate, firstBreaking) < 0;
}

void main() {
  final cases = [
    ('^1.2.3', '1.9.0'),
    ('^1.2.3', '2.0.0'),
    ('^1.2.3', '1.2.2'),
    ('^0.2.3', '0.2.9'),
    ('^0.2.3', '0.3.0'),
  ];
  for (final (constraint, version) in cases) {
    print('$constraint allows $version: ${allows(constraint, version)}');
  }
  try {
    allows('^1.2', '1.2.0');
  } on FormatException catch (e) {
    print('invalid: ${e.message}');
  }
}

Quick quiz 1 / 3

Which versions does the constraint http: ^1.4.2 allow?

Quick quiz 2 / 3

Which statement about pubspec.lock is right for a library package you will publish?

Quick quiz 3 / 3

When you depend on a package called other, which import is the risky one?

What to remember

  • pubspec.yaml holds the ranges you accept and pubspec.lock holds the exact versions pub chose
  • ^1.2.3 means >=1.2.3 <2.0.0, ^0.2.3 means >=0.2.3 <0.3.0, and any should be avoided
  • Export the public API from lib/, keep the implementation in lib/src/ and never import another package's src/
  • Run format, analyze and test before commit and in CI, and commit the lock file only for applications

Dart 3.13 changelog — Dart

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Packages, Pub & Project Tooling | Thuta Learning