preface

Import and library directives can help you create modular, shareable codebase. Libraries provide not only apis, but also units of privacy: identifiers beginning with an underscore (_) are visible only inside the library. Every Dart application is a library, even if it doesn’t use library directives.

Libraries can be distributed using packages.

Use the library

Use import to specify that the namespace of one library is used in the scope of another library.

For example, Dart Web applications typically use the Dart: HTML library, which can be imported like this:

import 'dart:html';
Copy the code

The only required argument to import is the URI specifying the library. For built-in libraries, urIs have a special DART :scheme. For other libraries, you can use file system paths or Package: Scheme. Package: The library specified by scheme is provided by a package manager, such as the pub utility. Such as:

import 'package:test/test.dart';
Copy the code

Note: URI stands for Uniform Resource Identifier (URI). A URL (Uniform resource Locator) is a common URI.

Specifies the prefix of a library

If you import two libraries that conflict, you can specify a prefix for one or both libraries. For example, if library1 and library2 both have Element classes, you might use the following code:

import 'package:lib1/lib1.dart';
import 'package:lib2/lib2.dart' as lib2;

// Use Element in lib1
Element element1 = Element(a);// Use Element in lib2
lib2.Element element2 = lib2.Element(a);Copy the code

Import only a portion of the library

If you only use part of the library, you can optionally import it, for example:

// Import only foo
import 'package:lib1/lib1.dart' show foo;

// Import everything except foo
import 'package:lib2/lib2.dart' hide foo;
Copy the code

Lazy loading of a library

Lazy loading (also known as lazy loading) allows a Web app to load only when the library is needed. Here are some situations where lazy loading may be used:

  • Reduce the initial startup time of a Web App
  • Do A/B testing – an algorithm to try alternatives
  • Load hard-to-use functions, such as the optional Screens and Dialogs

Lazy loading is supported only for dart2js. Flutter, Dart VM and DartDevc do not support lazy loading. For more information, see Question # 33118 and Question # 27776.

To lazily load a library, you must use Deferred As the first time you import it

import 'package:greetings/hello.dart' deferred as hello;
Copy the code

When you need the library, call loadLibrary() to use the library identifier.

Future greet() async {
  await hello.loadLibrary();
  hello.printGreeting();
}
Copy the code

In the previous code, the keyword await is paused until the library is loaded.

You can call loadLibray() to load a library multiple times, but the library will only be loaded once.

When you use lazy loading, remember:

  • A lazy-loaded library constant is no longer a constant during file import. Remember, these constants will not exist until the delay library is loaded.
  • You cannot use types in the deferred library during the import process. So consider moving the interface type into a library and importing both it and the delay library.
  • Dart implicit insertionloadLibrary()Use to your definitiondeferred as namespaceNamespace of.loadLibrary()The function returns aFuture

Implementing a library

The Dart ecosystem uses packages to share software, such as libraries and tools. This page shows you how to create a package, focusing on the most common package, library Package.

What does a library package consist of

The following illustration shows the structure of the simplest library package:

Minimum required for a library package:

Pubspec files Pubspec.yaml files are the same for both a library and an application package — there is no special design to distinguish a package from a library.

The lib directory, as you might expect, holds the library’s code and is open to other packages. You can create any level in the lib directory. For convenience, the implementation code is placed under lib/ SRC. Code in lib/ SRC can be considered private; Other packages do not need to import SRC /… . To make your lib/ SRC APIs public, you can export lib/ SRC files from a file directly in the lib directory.

Note: When the Library directive is not specified, a unique tag is generated for each library based on its path and file name. Therefore, we recommend that you omit library directives from your code unless you intend to generate library-level documentation.

Organize a library package

Library packages are easiest to maintain, extend, and test when creating small, single libraries (called mini-libraries). In most cases, each class should be in its own microlibrary, unless you have a tight coupling between two classes.

Note: You’ve probably heard of the Part directive, which splits the library into multiple Dart files. We recommend that you avoid using parts and instead create small libraries.

Dart creates a main library file directly under lib, lib/.dart, which will export all public apis. This allows the user to get all the functionality of the library by importing a single file.

The lib directory may also contain other non-SRC libraries that can be imported. For example, maybe your main library works cross-platform, but you create a separate library that relies on DART: IO or DART: HTML. Some packages have separate libraries, but if there is no main library, import with a prefix.

Let’s take a look at the structure of library packages in the real world: shelf. The Shelf package provides an easy way to create a Web server using Dart, laid out in the same structure as the Dart library package:

shelf.dart

export 'src/cascade.dart';
export 'src/handler.dart';
export 'src/handlers/logger.dart';
export 'src/hijack_exception.dart';
export 'src/middleware.dart';
export 'src/pipeline.dart';
export 'src/request.dart';
export 'src/response.dart';
export 'src/server.dart';
export 'src/server_handler.dart';
Copy the code

The Shelf package also includes a mini library: Shelf_io. This adapter handles HttpRequest objects from DART: IO.

Web application tip: For best performance when developing with DartDevc, put the implementation file under /lib/src and not somewhere else under /lib. Also, avoid importing package:package_name/ SRC /….

Import library file

When you import a library file, you can specify its URI directly using package:

import 'package:utilities/utilities.dart';
Copy the code

You can import a library using a relative path, whether the file is inside or outside the lib directory, but you must use package:. When in doubt, use the Package: directive directly, which works in all cases.

The following figure shows how to import lib/foo/ a.art from lib and the Web.

Note: Although lib graphics use relative imports (import’.. /foo/ a.art ‘) shows lib/bar/ b.art, but it can be replaced by the package: directive (import’package: my_package/foo/ a.art ‘).

Provide additional documentation

A well-designed library package is easy to test. We recommend that you write tests using the Test package and place the test code in the Test directory at the top of the package.

If you create any command-line tools for public use, place them in the bin directory, which is public. Use pub Global Activate to enable running tools from the command line. After listing the tool in the executable section of PubSpec, users can run it directly without calling pub Global Run.

It is useful to provide an example of how to use your library. You can place it in the package’s top-level directory, Example.

Any tools or executables you create during development that are not for public use can be placed in the Tool directory.

If the library is published to the Pub site, the additional files required (such as README and CHANGELOG) are described in the distribution package. For more information on how to organize package directories, see the PUB Package layout convention.

Write documents for a library

You can use the dartdoc tool to generate API documentation for your library. Dartdoc parses sources to find document comments using /// syntax:

/// Take care of updating the BADGE in UI
void updateBadge() {
  ...
}
Copy the code

See the Shelf documentation for an example of the generated documentation.

Note: To include any library level document in the generated document, you must specify the library directive. Please refer to question 1082.

Distributing open Source libraries

If your library is open source, we recommend sharing it on the Pub website. To publish or update the library, use Pub Publish, which uploads your package and creates or updates its pages. For example, see the Shelf package page. For more information on how to prepare packages to be published, see Publishing packages.

The publishing site not only hosts your package, but also generates and hosts the API reference documentation for your package. The About box in the package provides a link to the newly generated documentation; For example, see the API documentation for bookshelf packaging. Links to previous version documents in the Versions TAB of the package page.

To make sure your package’s API documentation looks good on the distribution site, follow these steps:

  • Before publishing the package, run the dartdoc tool to ensure that your document is generated successfully and looks as expected.
  • After you publish the package, check the Versions TAB to ensure that the document was successfully generated.
  • If the document is not generated at all, click Failed in the Versions TAB to see dartDoc output.

resources

Use the following resources to learn more about library packages:

  • Libraries and visibility in the language Guide covers the use of library files.
  • Package documentation is very useful, especially package layout conventions.
  • Content not committed covers content that should not be checked into the source code repository.
  • Newer library packages under the Dart-Lang organization tend to show best practices. Consider the following examples: Dart_style, PATH, shelf, source_gen, and test.