Libraries

Every Dart file is inherently a library, even without the library directive;

Privacy rule: Identifiers starting with underscore _ are library-private, only visible within the current library, inaccessible across files/libraries;

No public/protected/private keywords; access permissions are distinguished solely by underscores;

Libraries can be packaged into package and managed via pub;

Advantage: Enables Tree Shaking to eliminate unused dead code.

import

Use the import keyword to import other libraries.

import is used to introduce APIs from other libraries

Three types of URIs:

  1. dart:xxx: Dart built-in standard libraries (dart:core, dart:async, dart:js_interop)
  2. package:xxx: Third-party libraries managed by pub
  3. Relative file paths: Local custom .dart files
// Built-in standard libraries
import 'dart:js_interop';
import 'dart:math';

// Third-party packages
import 'package:test/test.dart';

// Local file libraries
import './utils.dart';Code language: JavaScript (javascript)

Library Aliases

When two libraries contain identical class/function names, use as alias to isolate and distinguish them.

Example

In lib1.dart

class Element {}Code language: JavaScript (javascript)

lib2.dart has the same class name

class Element {}Code language: JavaScript (javascript)

Main entry file main.dart

// Direct import, default namespace
import 'lib1.dart';
// Assign alias lib2
import 'lib2.dart' as lib2;

void main() {
  Element e1 = Element(); // Element from lib1
  lib2.Element e2 = lib2.Element(); // Element from lib2
}Code language: JavaScript (javascript)

To avoid naming conflicts, we assign alias lib2 to lib2.dart, then prefix all its classes with the alias when accessing.

Selective Import show / hide

show: Only import specified names, hide everything else

// Only import foo; other variables/classes unavailable
import 'lib1.dart' show foo;

void main() {
  foo();
  // bar(); // Error, not imported via show, inaccessible
}Code language: JavaScript (javascript)

hide: Import everything except the specified names

// Import all, block only foo
import 'lib2.dart' hide foo;

void main() {
  bar();
  // foo(); // Error, blocked by hide
}Code language: JavaScript (javascript)

Deferred Loading deferred as

Only effective on Web platform

  • Reduce initial webpage load size;
  • For low-frequency popups, optional pages;
  • Dynamically download code chunks on demand.
  1. Import syntax: import path deferred as namespace
  2. Call namespace.loadLibrary() which returns a Future, use await to wait for loading completion
  3. Multiple calls to loadLibrary() for the same library only trigger one load
  4. Limitation: Constants and types inside deferred libraries cannot be used directly before loading

Full Example

hello.dart (deferred library)

void printGreeting() {
  print("Hello from deferred library wellcome to foxdevelop.com");
}
Code language: JavaScript (javascript)

main.dart

// Deferred import with alias hello
import 'hello.dart' deferred as hello;

Future<void> greet() async {
  // Dynamically load library
  await hello.loadLibrary();
  // Can call internal methods only after loading finishes
  hello.printGreeting();
}

void main() async {
  await greet();
}
Code language: JavaScript (javascript)

Output:

Hello from deferred library wellcome to foxdevelop.com
Code language: JavaScript (javascript)

Place both files in the same folder

What if hello.dart is in another directory, e.g. upper lib folder?

Path example: D:\dartdemo\firstdart\lib

main.dart located at D:\dartdemo\firstdart\bin

firstdart/
├─ bin/
│  └─ firstdart.dart       // Program entry point
└─ lib/
   └─ hello.dart      // Deferred loading libraryCode language: JavaScript (javascript)

Import statement:

// ../ represents parent directory
import '../lib/hello.dart' deferred as hello;Code language: JavaScript (javascript)

Top-level library declaration library

Written at the very top of the file, used for library documentation comments and library-level annotations (e.g. test platform restrictions).

/// Browser-only test utility library
@TestOn('browser')
library;
Code language: JavaScript (javascript)

export

Export (encapsulate unified public APIs)

Commonly used for tool packages, aggregate multiple sub-libraries and expose only one single import entry externally.

File Structure

src/math.dart

int add(int a, int b) => a + b;
int sub(int a, int b) => a - b;
Code language: PHP (php)

src/string.dart

String upper(String s) => s.toUpperCase();
Code language: JavaScript (javascript)

utils.dart (unified export entry)

export 'src/math.dart';
export 'src/string.dart';
// Hide internal private utilities
export 'src/internal.dart' hide helper;
Code language: JavaScript (javascript)

utils.dart cannot run alone — it is merely an aggregation export file with no main() entry function; you cannot run dart run lib/utils.dart;

Purpose of export

  • Aggregate APIs from multiple src sub-files;
  • Users only need to import utils.dart to access all exposed methods;
  • hide xxx blocks internal tools, encapsulates implementation details and controls exposed public APIs.

Usage in main.dart

import 'utils.dart';

void main() {
  print(add(1,2));
  print(upper("dart"));
}
Code language: JavaScript (javascript)

Notes

export/import only handle source-level import and export — distributing .dart source files lets others view full source code;

To hide source code, you must not publish .dart sources, only distribute compiled binary Snapshots.

A Snapshot is a compiled binary file from Dart; others cannot fully reverse-engineer readable source code, only call exposed public APIs.

This topic is covered in other courses.

part

Split one library across multiple files

Split a single library into multiple files that share underscore-prefixed private identifiers. Must pair part 'xxx.dart' / part of 'main_file.dart'

main_lib.dart (main library file)

library; // Declare this is a library
part 'logic.dart'; // Merge logic.dart into current main_lib.dart, they belong to the same library

int _secret = 999; // Library-private variable
Code language: JavaScript (javascript)

logic.dart (partial split file)

part of 'main_lib.dart'; // Declare this file belongs to main_lib.dart, not an independent library.

void printSecret() {
  // Can access _secret from main file; private identifiers are shared within the same library
  print(_secret);
}
Code language: JavaScript (javascript)

Invocation

import 'main_lib.dart'; // Import main library, do NOT import partial split files

void main() {
  printSecret(); // Output 999
}
Code language: JavaScript (javascript)

Conditional Imports

Automatically switch implementation files based on platform

import 'platform_stub.dart'
    if (dart.library.io) 'platform_mobile.dart'
    if (dart.library.js_interop) 'platform_web.dart';
Code language: JavaScript (javascript)

Previous:
Next:

Leave a Reply

Your email address will not be published. Required fields are marked *