Importing path variants

In the previous examples, we imported a local file library that lives in the same directory as the library customer, so we just specified the filename.

However, that's not the case for when you are using third-party Dart packages. In this case, the files will not exist in the same directory, so let's take a look at how we can import an outer package Dart library.

There are several ways to specify library paths in the import statement, and we have already used two of them: relative file import and importing from a package. Now, let's take a look at all of them in more detail.

Let's assume that we have a package directory of a small foo package containing two files: a.dart and b.dart. To import them, we can use multiple approaches:

  • A relative file path: This is similar to the method that we used in the previous example, as the libraries were in the same folder. We can just put the relative path to the library file we want to import, as follows:
import 'foo/a.dart';
import 'foo/b.dart';
  • An absolute file path: We can add the absolute path on the computer to a library file by adding the file:// URI prefix to the import path:
import "file:///c:/dart_package/foo/a.dart";
import "file:///c:/dart_package/foo/b.dart";
Although possible, absolute importing is not recommended and it is a bad way to import libraries as, in distributed development environments, it will likely cause problems when locating files.
  • A URL over the web: In the same way as using an absolute file path, we can add the URL of a website containing the source code of a library directly over the http:// protocol:
  import "http://dartpackage.com/dart_package/foo/a.dart";
  • A package: This is the most common way to import a library. Here, we specify the library path from the package root. We will explore the packages definition later in this chapter; in the case of importing a local library, it goes from the root of the package, down the source tree until the library file:
import 'package:my_package/foo/a.dart';
import 'package:my_package/foo/b.dart';

The package method is the recommended way to import libraries, as it works well with local libraries (that is, your project's local files and libraries) and is the way to use the provided libraries from third-party packages.

Feel free to revisit the example of the package after you learn what a package is in the Dart context. You can find the source code of this chapter on GitHub.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.163.58