Dart Libraries & Packages
pubspec.yaml file and shared through pub.dev. This lesson covers imports, privacy, how to structure a package's public API, and how to manage dependencies with the dart pub tool.
Libraries and Privacy
A Dart library is simply a .dart file. Unlike Java or C#, Dart has no public, private or protected keywords. Visibility is decided by the name: an identifier that starts with an underscore (_) is private to its library, and everything else is public.
Underscore Means Library-Private
// lib/src/cart.dart
class Cart {
final List<double> _prices = []; // private: invisible outside this file
void add(double price) => _prices.add(price);
double get total => _round(_prices.fold(0.0, (sum, p) => sum + p));
}
double _round(double value) => (value * 100).round() / 100; // private top-level function
Privacy is per library, not per class: other code in the same file can read _prices. This is deliberate — a library is the unit of encapsulation. Keep files focused, so that what is private to the file is private to one idea.
The Core Libraries
| Library | Provides | Platforms |
|---|---|---|
dart:core | Numbers, strings, collections, print — imported automatically | all |
dart:async | Future, Stream, timers | all |
dart:math | Constants, Random, min/max, trigonometry | all |
dart:convert | JSON and UTF-8 encoding and decoding | all |
dart:collection | Queues, linked hash maps, splay trees | all |
dart:io | Files, processes, sockets, HTTP server | native (not web) |
dart:js_interop | Calling JavaScript; used with package:web for browser APIs | web |
Older tutorials use dart:html for browser code; it is deprecated in favor of package:web and dart:js_interop, which also work when compiling to WebAssembly.
Importing Libraries
An import directive makes another library's public names available. The URI tells Dart where to find it: dart: for the SDK, package: for libraries in a package, and a relative path for files in the same package.
import 'dart:math'; // SDK library
import 'dart:convert' show jsonDecode; // import only one name
import 'package:http/http.dart' as http; // prefix: http.get(...)
import 'src/cart.dart' hide Cart; // everything except Cart (relative URI)
void main() {
final rng = Random(42); // from dart:math
print(rng.nextInt(100) < 100); // true
final data = jsonDecode('{"qty": 3}') as Map<String, dynamic>;
print(data['qty']); // 3
}
Prefixes, show and hide
Two libraries may export the same name. A prefix (as http) avoids the clash and makes the origin of every call visible, which is the recommended style for packages with generic names such as get or Client. show imports only the listed names and hide imports all but the listed names; both keep a file's namespace small and its dependencies explicit.
Deferred Loading
On the web, import 'package:charts/charts.dart' deferred as charts; splits the library into a separate download that is fetched when you call await charts.loadLibrary(). This shrinks the initial page load for rarely used features. Deferred loading is designed for web builds: the Dart VM loads such libraries immediately, and Flutter uses its own deferred-components mechanism on Android.
Packages
A package is a directory with a pubspec.yaml file. Applications and reusable libraries are both packages; the difference is only whether other packages depend on it.
Package Layout
shop_math/
├── pubspec.yaml # name, SDK constraint, dependencies
├── lib/
│ ├── shop_math.dart # the public entry point: package:shop_math/shop_math.dart
│ └── src/ # implementation files; private by convention
│ ├── cart.dart
│ └── tax.dart
├── bin/ # command-line entry points (main functions)
├── test/ # tests run with: dart test
└── example/ # usage examples shown on pub.dev
Everything under lib/ can be imported by other packages with a package: URI. By convention, code under lib/src/ is implementation detail: other packages should not import it, and the recommended lint set (implementation_imports) warns when they do.
Building a Public API with export
The entry-point library re-exports exactly what users should see. Users then need a single import, and the package can rearrange src/ freely without breaking them.
// lib/shop_math.dart: the package's public API
library;
export 'src/cart.dart' show Cart;
export 'src/tax.dart' show vatFor, TaxRate;
// bin/main.dart, or any package that depends on shop_math:
// import 'package:shop_math/shop_math.dart';
The part and part of directives can split one library across several files, but they are now used almost only by code generators such as json_serializable. For hand-written code, prefer small libraries combined with export.
Managing Dependencies with pub
The pubspec.yaml file declares the package's name, the Dart SDK versions it supports, and its dependencies. Packages under dev_dependencies are needed only for development, such as test frameworks and linters.
name: shop_app
description: A small command-line shop.
version: 1.0.0
publish_to: none # an application, not meant for pub.dev
environment:
sdk: ^3.5.0 # Dart 3.5 up to, but not including, Dart 4
dependencies:
http: ^1.2.0 # at least 1.2.0, below 2.0.0
dev_dependencies:
lints: ^5.0.0
test: ^1.25.0
Everyday Commands
dart pub add http # add a dependency to pubspec.yaml and fetch it
dart pub add --dev test # add a development-only dependency
dart pub get # fetch the versions recorded in pubspec.lock
dart pub upgrade # move to the newest versions the constraints allow
dart pub outdated # list dependencies with newer versions available
The caret syntax ^1.2.0 follows semantic versioning: any version from 1.2.0 up to, but not including, the next major version. dart pub get writes the exact versions chosen to pubspec.lock; commit that file for applications so every build uses the same dependency graph. The general practice is covered in Release Management.
Choosing Packages
Every dependency is code you ship and must keep updated. Before adding one, check its page on pub.dev: a verified publisher, recent releases, a high pub points score (documentation, static analysis, platform support), support for the platforms you target, and an acceptable license. Prefer the SDK and a few well-maintained packages over many small ones.
Practice
Exercises
- Create a package with
dart create -t package shop_math, move a class intolib/src/, and export it fromlib/shop_math.dart. - Add a private helper function to one file and try to call it from another file in the same package; read the analyzer error.
- Create an application with
dart create shop_app, addhttpwithdart pub add http, import it with a prefix, and fetch a page withhttp.get. Then inspectpubspec.lockto see which versions were chosen.
Next: Dart Deployment builds and ships these packages.