Sub topic 16
Libraries, Imports, and Packages
This chapter assumes you can write classes and functions, know how main() works, and have a working Dart SDK with dart on your path. You don't need any Flutter knowledge. Flutter projects use the same mechanisms, so what you learn here applies directly to them.
Every file is a library
In Dart, each .dart file is a library. A library is the unit of code sharing and of privacy. There is no public or private keyword. A name that starts with an underscore (_) is private to its library, and every other name is visible to anyone who imports the library.
Privacy is per library, not per class. Two classes in the same file can read each other's _fields. Code in another file can't, even from a subclass.
class Counter {
int _count = 0;
void increment() => _count++;
int get count => _count;
}
class Inspector {
// Legal: same file, so same library.
int peek(Counter c) => c._count;
}
void main() {
final c = Counter()..increment();
print(Inspector().peek(c));
}If Inspector lived in another file, c._count would be a compile error.
Import forms
An import makes another library's public names available in the current file. The URI after import takes one of three forms:
| Form | Example | Use for |
|---|---|---|
| `dart:` | `import 'dart:math';` | SDK libraries |
| `package:` | `import 'package:http/http.dart';` | Code from a package, including your own |
| Relative path | `import 'src/geometry.dart';` | Files in the same package |
dart:core (with int, String, List, Future, Stream and others) is imported automatically. You must import others yourself. Common ones are dart:async (for StreamController and Timer), dart:convert (JSON and UTF-8), dart:math, and dart:io. dart:io works on the command line and on mobile and desktop, but not in a browser.
Prefixes, show, and hide
Two libraries can export the same name. If you import both and use the name, the compiler reports an ambiguous import. Three tools resolve this:
asgives the whole library a prefix.showimports only the listed names.hideimports everything except the listed names.
dart:math already defines a class called Point. If you also write or import your own Point, you have a clash:
import 'dart:math' hide Point;
import 'package:shapes_demo/shapes_demo.dart';
void main() {
const p = Point(1, 2); // our Point, no ambiguity
print(p.x);
}Prefixing is often clearer, because the reader can see where each name comes from. The usual convention is import 'dart:math' as math; and then math.sqrt(...). Prefix names use lowercase_with_underscores.
Deferred imports
import '...' deferred as name; delays loading a library until you call await name.loadLibrary();. It is mainly useful in web apps, to shrink the first download. On other platforms the code is loaded normally.
Conditional imports
A conditional import picks a file based on the platform. The stub below is selected unless dart:io is available:
import 'storage_stub.dart'
if (dart.library.io) 'storage_io.dart'
if (dart.library.js_interop) 'storage_web.dart';All the candidate files must expose the same API. Packages that support both web and native code use this pattern.
Building your own library with export
An export directive re-exports another library's names to anyone who imports yours. The usual layout for a package puts the implementation in lib/src/ and exposes a chosen public surface from a single file in lib/.
The example package is called shapes_demo. Its layout is:
shapes_demo/
pubspec.yaml
lib/
shapes_demo.dart
src/
geometry.dart
bin/
main.dart
test/The implementation file:
// lib/src/geometry.dart
import 'dart:math' as math;
class Point {
final double x;
final double y;
const Point(this.x, this.y);
}
double _square(double v) => v * v;
double distance(Point a, Point b) =>
math.sqrt(_square(a.x - b.x) + _square(a.y - b.y));The public entry point, sometimes called a barrel file:
// lib/shapes_demo.dart
export 'src/geometry.dart' show Point, distance;A program that uses the package:
// bin/main.dart
import 'package:shapes_demo/shapes_demo.dart';
void main() {
const a = Point(0, 0);
const b = Point(3, 4);
print(distance(a, b)); // 5.0
}Everything in lib/src/ is treated as implementation detail by convention. Other packages should not import package:shapes_demo/src/... directly, because you are free to change those files without a version bump. The show on the export list keeps even public names in src from leaking out accidentally.
Packages and pubspec.yaml
A package is a directory with a pubspec.yaml file. It is the unit of distribution, versioning, and dependency management. Packages are published on pub.dev, and the dart pub tool (or flutter pub in a Flutter project) resolves and downloads them.
name: shapes_demo
description: Small geometry helpers.
version: 1.0.0
environment:
sdk: ^3.0.0
dependencies:
collection: ^1.18.0
dev_dependencies:
test: ^1.24.0Key points about this file:
nameis what appears afterpackage:in imports. It must be lowercase with underscores.dependenciesare needed at runtime.dev_dependenciesare needed only for development, such as tests and code generators.- A caret constraint such as
^1.18.0means>=1.18.0 <2.0.0. For versions below 1.0, the caret is stricter:^0.2.3means>=0.2.3 <0.3.0. environment.sdkstates which Dart versions the package supports. Language features like records and sealed classes require^3.0.0or later.
The commands you will use most:
dart pub add http # add a dependency and fetch it
dart pub get # resolve and download what pubspec.yaml lists
dart pub upgrade # move to the newest versions the constraints allow
dart pub outdated # show which dependencies have newer releases
dart run bin/main.dart # run a file with the package config in placeIn a Flutter project, use flutter pub add and flutter pub get. They run the same resolver.
dart pub get also writes pubspec.lock, which records the exact version of every dependency, including indirect ones. Commit it for applications so every build uses the same versions. Libraries that others will depend on normally leave it out of version control, because their users' resolvers pick the versions.
Part files
part and part of split one library across several files. All the files share one namespace, including private names:
// user.dart
part 'user.g.dart';
class User {
final String name;
User(this.name);
}// user.g.dart
part of 'user.dart';
String describe(User u) => 'User ${u.name}';Hand-written code rarely needs this, since separate libraries with exports are easier to reason about. You will mostly see it in generated code. Flutter packages such as json_serializable and freezed generate a *.g.dart or *.freezed.dart part file next to your source.
Common errors and gotchas
| Symptom | Cause | Fix |
|---|---|---|
| `Target of URI doesn't exist: 'package:foo/foo.dart'` | The dependency is missing from `pubspec.yaml`, or `pub get` was not run | `dart pub add foo`, then `dart pub get` |
| `The name 'Point' is defined in the libraries ...` | Two imports export the same name | Use `as`, `show`, or `hide` |
| `The getter '_x' isn't defined` | You used a private name from another library | Expose it through a public member |
| Unused import warning | An import has no references in the file | Delete it |
| Same class seems to be "two different types" | One file imports it via a relative path and another via `package:` | Use one consistent style |
The last row matters in practice. The analyzer treats package:app/models.dart and ../models.dart as two different URIs. The style guide's rule is to use relative imports for files inside lib/, and package: imports for anything that reaches into lib/ from bin/, test/, or another package. Never mix the two for the same target in one package.
Import cycles between libraries are legal in Dart, but they usually signal that shared code should move to a third library.
Exercise
In dart:math there is a class called Point, and your own package also exports Point. Write the import lines for a file that needs your Point plus sqrt from dart:math, in two ways: one using hide, one using a prefix. Show how each version calls sqrt and creates a point.
Show answer
With hide: import 'dart:math' hide Point; and import 'package:shapes_demo/shapes_demo.dart';. Call sqrt(16) and const Point(1, 2) directly. With a prefix: import 'dart:math' as math; and the same package import. Call math.sqrt(16) and const Point(1, 2). In both versions Point refers to your class, because the dart:math one is either hidden or only reachable as math.Point.
Exercise
A package has lib/src/parser.dart containing class Parser and a private function _trim. The file lib/my_pkg.dart contains only export 'src/parser.dart' show Parser;. Can code in another package call _trim, and can it import package:my_pkg/src/parser.dart directly? What are the consequences?
Show answer
It cannot call _trim, because the underscore makes it private to the parser.dart library, and exports never change that. It can technically import package:my_pkg/src/parser.dart because Dart does not enforce src privacy, but doing so breaks the convention. The author may rename or remove anything in src/ in a minor release, so that import can break on a routine upgrade.