Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 61 ยท Errors and Libraries

Libraries, Imports and Packages

Learn how Dart organizes code into libraries and packages: import, as, show, hide, deferred loading, export, part files, pubspec.yaml, version constraints and pub.dev.

Every Dart file is part of a library, and every library you use in a real project lives in a package. A library is a unit of code you can import. A package is a folder with a pubspec.yaml file that other projects can depend on. Once your program grows beyond one file, these two ideas decide how you split code, what other code can see, and how you borrow work from the community.

The Dart code in this lesson is read-only, because the site cannot run the Dart tools. The TypeScript stand-ins use ES module imports, which work in a very similar way, so you can see aliases, selective imports and lazy loading in action.

Importing a library

You bring a library into a file with import and a URI. Three kinds of URI are common:

DART
import 'dart:math';                          // a library from the Dart SDK
import 'package:http/http.dart';             // a library from a package
import 'src/helpers.dart';                   // a relative path to your own file

void main() {
  print(sqrt(144));    // 12.0, from dart:math
}

dart:core is imported into every file automatically. That is why print, String, List and int work without any import.

Inside your own package you can import files either with a relative path ('src/helpers.dart') or with a package: URI that starts with your package name ('package:my_app/src/helpers.dart'). Pick one style per package and stay consistent. Files under lib/ should not reach into bin/ or test/, and code outside lib/ should use package: imports to reach into lib/.

Prefixes, show and hide

Two libraries can export the same name. Imagine a Client class in both package:http/http.dart and some other package. Give one of them a prefix with as:

DART
import 'dart:math' as math;
import 'package:http/http.dart' as http;

void main() {
  var biggest = math.max(3, 9);
  var client = http.Client();    // always written with the prefix
  client.close();
  print(biggest);
}

You can also import only part of a library with show, or everything except some names with hide:

DART
import 'dart:math' show Random, pi;          // only Random and pi
import 'dart:io' hide exit;                  // everything except exit

void main() {
  var dice = Random();
  print(dice.nextInt(6) + 1);   // 1 to 6
  print(pi);                    // 3.141592653589793
}

A prefix is the safest tool when names clash. show and hide are good for documenting what a file really needs, and for quietly resolving one clash. If you write import 'a.dart'; import 'b.dart'; and both define parse, the analyzer reports an ambiguous import until you fix it with a prefix or hide.

TypeScript Aliases, show and hide (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Privacy: the library is the boundary

Dart has no public or private keywords. Instead, a name that starts with an underscore is private to its library, which usually means private to its file:

DART
// lib/src/counter.dart
class Counter {
  int _count = 0;                 // private: invisible outside this file
  int get count => _count;
  void increment() => _count++;
}

String _label(int n) => 'Count: $n';   // private top-level function

Code in another file can use Counter, count and increment, but not _count or _label. Note that privacy applies to the whole file: two classes in the same file can read each other's underscore members. That is a feature, because closely related classes can cooperate without opening their internals to everyone. The Getters and Setters lesson shows the same rule from the class side.

Exporting and package layout

A library can re-export other libraries with export. Packages use this to offer one clean entry point while keeping the code in lib/src/:

DART
// lib/shapes.dart: the public face of the package
export 'src/circle.dart';
export 'src/square.dart' show Square;     // export only Square

The convention is simple. Everything under lib/src/ is an implementation detail. Anything you want users to import is exported from a top-level file in lib/. A standard package looks like this:

flowchart TD
    P["my_app/"] --> Y["pubspec.yaml<br/>name, version, dependencies"]
    P --> L["lib/<br/>public API"]
    L --> S["lib/src/<br/>private code"]
    P --> B["bin/<br/>command-line entry points"]
    P --> T["test/<br/>tests"]
    P --> A["analysis_options.yaml<br/>lint rules"]

A typical Dart package: public code in lib/, internals in lib/src/, programs in bin/ and tests in test/.

Two more directives exist, and you will mostly meet them in older or generated code:

  • library; (optional, usually only needed to attach a doc comment or an annotation to the library).
  • part 'file.g.dart'; plus part of 'main.dart'; in the other file. A part file is textually joined to its main library and shares its private names. It is mainly used by code generators; prefer ordinary libraries for your own code.

Deferred (lazy) loading

On the web, a big program can be split into pieces that download on demand. Mark an import deferred as and load it when needed:

DART
import 'package:charts/heavy_charts.dart' deferred as charts;

Future<void> showReport() async {
  await charts.loadLibrary();      // download and initialize now
  charts.drawBarChart([1, 2, 3]);
}

A few rules apply. You must call loadLibrary() before using anything from the library. Calling it again is harmless. Constants and types from a deferred library cannot be used in the importing file before it is loaded. On the Dart VM and in native Flutter apps, the code is simply loaded straight away, so deferred loading only saves download size when you compile to JavaScript.

TypeScript Loading code on demand (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Conditional imports are a related tool: import 'stub.dart' if (dart.library.io) 'native.dart' if (dart.library.js_interop) 'web.dart'; picks a different file depending on the platform. Packages that run on both Flutter mobile and the web use this pattern.

Packages and pubspec.yaml

The pubspec.yaml file describes a package. Here is a small one:

YAML
name: weather_cli
description: A command-line weather tool.
version: 1.0.0
publish_to: none            # an app: never publish it to pub.dev

environment:
  sdk: ^3.5.0               # needs Dart 3.5 or newer, below 4.0

dependencies:
  http: ^1.2.0
  args: ^2.5.0

dev_dependencies:
  test: ^1.25.0
  lints: ^5.0.0

dependencies are needed by the code you ship. dev_dependencies are only for development: tests, lints, code generators. The ^1.2.0 form is a caret constraint: any version from 1.2.0 up to, but not including, 2.0.0. Under semantic versioning, a new major version may break your code, and minor and patch versions should not.

You rarely edit the dependency list by hand. The tooling does it for you:

SH
dart pub add http          # adds the latest compatible version to pubspec.yaml
dart pub add --dev test    # adds a dev dependency
dart pub get               # downloads packages, writes pubspec.lock
dart pub upgrade           # moves to the newest versions allowed by your constraints
dart pub outdated          # shows what could be upgraded, and what is blocked

pubspec.lock records the exact versions that were chosen. Commit it for applications so every machine builds with the same versions. For a package that other people depend on, the lock file is optional, because their own lock file decides.

TypeScript What does a caret constraint allow? (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Finding packages on pub.dev

pub.dev is the official package repository. Each package page shows a pub points score (documentation, platform support, static analysis), a popularity figure, likes, the supported platforms and a changelog. Before you add a dependency, check these things:

  1. Is it maintained? Look at the date of the last release and the open issues.
  2. Does it support your platforms (VM, Flutter, web)?
  3. Does it have a verified publisher or many likes?
  4. Is the license compatible with your project?
  5. How many dependencies does it pull in? Fewer is usually safer.

Every dependency is code you did not write but now ship. Prefer the SDK libraries and a few well-known packages over a long list of small ones. Packages from the Dart team itself (such as args, http, path, collection, test) are a good place to start. The next lesson tours the libraries that need no package at all: Core Libraries.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you make a top-level name private to its library in Dart?

    A leading underscore makes a name library-private. Dart has no private or public keywords. The lib/src/ folder is only a convention, not an access rule.
  2. 2. Two imported libraries both define a class named Client. What is the cleanest fix?

    A prefix with as keeps both libraries usable: you write a.Client and the other Client without a conflict.
  3. 3. What does the constraint http: ^1.2.0 allow?

    The caret allows compatible updates: same major version, at least 1.2.0. A new major version (2.0.0) is excluded because it may break your code.
  4. 4. When does a deferred as import actually reduce what the user downloads?

    Deferred loading splits web output into separately downloaded parts. On the VM and in native Flutter apps the code is loaded immediately, so there is no size benefit.
  5. 5. Which file records the exact dependency versions chosen by dart pub get?

    pubspec.lock stores the resolved versions. pubspec.yaml holds the ranges you allow. Commit the lock file for applications.

Summary

  • A Dart file is a library; a package is a folder with pubspec.yaml. dart:core is imported automatically.
  • Use as for prefixes, show and hide for selective imports, and export to build a clean public API from lib/src/.
  • Names starting with _ are private to the library (usually the file).
  • deferred as plus loadLibrary() loads code on demand and helps mainly in web builds.
  • dart pub add, get, upgrade and outdated manage dependencies; ^1.2.0 allows compatible updates; commit pubspec.lock for apps.
  • Judge a pub.dev package by maintenance, platform support, score, license and its own dependencies.

Next, see what the SDK gives you for free in Core Libraries.