Libraries, packages and pub

Dart · Practical · 12 min

Real projects depend on packages from pub.dev and are split into libraries with clear public APIs.

Every Dart file is a library. import brings in another library's public names:

  • import 'dart:math'; — core libraries.
  • import 'package:http/http.dart' as http; — a package, with a prefix to avoid name clashes.
  • import 'src/utils.dart'; — a relative path within your package.
  • show and hide limit which names are imported: import 'dart:math' show max, pi;.

Privacy is per library: _names are private to the file. Big libraries can be split with part/part of, but most code just uses separate libraries. A package's public API lives in lib/, with implementation in lib/src/ and a top-level file that exports what users should see.

A package is a directory with a pubspec.yaml declaring its name, SDK constraint (environment: sdk: ^3.9.0), dependencies and dev_dependencies. Version constraints use caret syntax: http: ^1.2.0 means at least 1.2.0 but below 2.0.0.

Commands:

  • dart create my_app — new project.
  • dart pub add http / dart pub add --dev test — add dependencies.
  • dart pub get — resolve and download; writes pubspec.lock (commit it for apps).
  • dart pub outdated and dart pub upgrade.
  • dart run, dart analyze, dart format, dart fix --apply.

analysis_options.yaml configures the analyzer; package:lints provides recommended rules.

Example

# pubspec.yaml
name: weather_cli
description: A tiny command-line weather client.
version: 1.0.0
environment:
  sdk: ^3.9.0

dependencies:
  http: ^1.2.0
  args: ^2.5.0

dev_dependencies:
  lints: ^5.0.0
  test: ^1.25.0

# lib/weather_cli.dart (the package's public API):
#   export 'src/client.dart' show WeatherClient;
# bin/main.dart:
#   import 'package:weather_cli/weather_cli.dart';
#   import 'package:http/http.dart' as http;
#   import 'dart:math' show max;
# Commands: dart pub get · dart run · dart analyze · dart test

Remember

  • import ... as p and show/hide control names
  • Public API in lib/, internals in lib/src/, re-exported with export
  • ^1.2.0 allows compatible updates below 2.0.0

Watch out for

  • Importing another package's src/ files directly — they're private implementation details.

Check yourself

  1. What versions does the constraint `http: ^1.2.0` allow?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: dart.dev/tools/pub/packages