Libraries, Imports and Visibility

29.1 Imports

Every Dart file is a library. Privacy (_name) is per library.

import 'dart:math';                              // core library
import 'package:http/http.dart' as http;         // package with a prefix
import 'package:my_app/src/utils.dart';          // your own package (lib/ is the package root)
import 'models/user.dart';                       // relative import
import 'dart:convert' show jsonDecode, jsonEncode;   // only these names
import 'package:collection/collection.dart' hide IterableExtension;
import 'package:heavy/heavy.dart' deferred as heavy; // lazy loading (web)

Future<void> loadHeavy() async {
  await heavy.loadLibrary();
  heavy.run();
}

29.2 Exports and Library Organization

// lib/my_package.dart: the public API entry point
library;                                         // optional library directive (unnamed)
export 'src/models.dart';
export 'src/client.dart' show ApiClient;
// Implementation lives in lib/src/ (by convention, private to the package)

29.3 part / part of

Prefer small libraries plus exports. part is mainly used by code generators.

// user.dart
part 'user.g.dart';                              // generated code shares privacy with this library
class User { /* ... */ }

// user.g.dart
part of 'user.dart';

29.4 Conditional Imports

import 'storage_stub.dart'
    if (dart.library.io) 'storage_io.dart'
    if (dart.library.js_interop) 'storage_web.dart';