TExcelTAD
Home › Dart › Libraries & Imports

Libraries & Imports

As a program grows, you split it into files. In Dart, every .dart file is a library. Libraries are the unit of code organisation and privacy: a name starting with _ is visible only inside its own library. You connect libraries with import (and, for package authors, export).

Importing core libraries

Libraries from the SDK use the dart: scheme. Only dart:core (with print, String, List, …) is imported automatically.

dart · try it yourself
import 'dart:math';
import 'dart:collection';
import 'dart:convert';

void main() {
  print(max(4, 9));
  print(sqrt(81));

  final queue = Queue<String>()..addAll(['first', 'second']);
  queue.addFirst('urgent');
  print(queue.removeFirst());

  print(jsonEncode({'ok': true}));
}
9
9.0
urgent
{"ok":true}
Library Contains
dart:core Built-in types, collections, print, DateTime, Uri, RegExp (auto-imported)
dart:async Future, Stream, Completer, Timer, StreamController
dart:math min, max, sqrt, pi, Random, Point
dart:convert JSON, UTF-8, Base64 codecs
dart:collection Queue, LinkedHashMap, SplayTreeMap, UnmodifiableListView
dart:io Files, sockets, HTTP server, processes (not on the web)
dart:isolate Isolates and ports
dart:typed_data Uint8List and friends for binary data

Importing your own files

A project with two files might look like this:

dart
// lib/pricing.dart
const vatRate = 0.08;

double withVat(double net) => _round(net * (1 + vatRate));

double _round(double v) => (v * 100).round() / 100; // private to pricing.dart
dart
// bin/shop.dart
import 'package:shop/pricing.dart';

void main() {
  print(withVat(100)); // 108.0
  // _round(1.234);    // error: _round is private to pricing.dart
}
Import form Points to
import 'dart:math'; An SDK library
import 'package:shop/pricing.dart'; lib/pricing.dart of the package named shop (your own or a dependency)
import 'utils.dart'; A relative path from the current file

Tip: Inside lib/, either style works — just be consistent. From bin/ and test/, use package: imports to reach code in lib/.

Controlling names: as, show, hide

Two libraries may define the same name. Use a prefix or limit what you import:

dart · try it yourself
import 'dart:math' as math;
import 'dart:convert' show jsonEncode, jsonDecode;
import 'dart:collection' hide LinkedList;

void main() {
  // `math.` makes the origin of each name obvious
  print(math.pi.toStringAsFixed(3));
  print(math.min(3, 7));

  final data = jsonDecode('[1, 2, 3]') as List;
  print(jsonEncode(data.reversed.toList()));

  final ordered = SplayTreeMap<String, int>()
    ..['pear'] = 3
    ..['apple'] = 5;
  print(ordered);
}
3.142
3
[3,2,1]
{apple: 5, pear: 3}
Syntax Effect
import 'x.dart' as x; Access everything as x.name
import 'x.dart' show a, b; Import only a and b
import 'x.dart' hide c; Import everything except c

Privacy is per library

Since privacy is per file, classes in the same file can see each other's private members — but other files can't. This example, in one file, is allowed:

dart · try it yourself
class Vault {
  final String _secret;
  Vault(this._secret);
}

class Inspector {
  // Same library, so _secret is accessible here
  String peek(Vault v) => v._secret.replaceRange(2, null, '***');
}

void main() {
  print(Inspector().peek(Vault('hunter2')));
}
hu***

Exporting a public API

Packages usually keep implementation files under lib/src/ and expose a single entry library that exports the public parts:

dart
// lib/shop.dart — what users import
library;

export 'src/cart.dart';
export 'src/pricing.dart' show withVat;   // re-export only part of a file
text
shop/
├── lib/
│   ├── shop.dart          ← import 'package:shop/shop.dart';
│   └── src/
│       ├── cart.dart
│       └── pricing.dart
├── bin/shop.dart
└── test/cart_test.dart

Users write one import, and you're free to reorganise src/ without breaking them.

part / part of

part splits one library across several files that share privacy. Today it's used mostly by code generators (e.g. user.g.dart from json_serializable):

dart
// user.dart
part 'user.g.dart';   // generated code can access _private members here

Deferred (lazy) loading

On the web, import 'big.dart' deferred as big; loads a library only when you call await big.loadLibrary() — reducing the initial download size.

Test yourself

Which library is imported automatically into every Dart file?

  1. dart:io
  2. dart:core
  3. dart:async
  4. dart:math

What does import 'dart:math' as math; require?

  1. Using math. before names from that library
  2. Importing only math
  3. Nothing — it's the same as a plain import
  4. Renaming the file

Where is a name like _helper visible?

  1. Everywhere in the package
  2. Only inside its own library (file)
  3. Only inside its class
  4. Only in tests