Mastering import

The import directive in Dart, as is the case in many other modern language, doesn’t only handle inclusion of external library files in the code like the good old C #include: it can do more than that to make our life easier when dealing with libraries and packages.

The Basics

We’ll start with the basics: importing an entire file to the current namespace.

Importing a Local File

You can import another local Dart file by using a relative path to it:

 import​ ​'filename.dart'​;

Importing a Built-In Dart Library

You can import a built-in Dart library by prefacing the name of the library with dart::

 import​ ​'dart:async'​;

Importing from a Package

You can import a file from a package by using:

 import​ ​'package:packagename/filename.dart'​;

Which can be used to import files from the Flutter SDK by using flutter as the package name:

 import​ ​'package:flutter/services.dart'

This syntax can also be used to import files in the app’s lib directory by using the app’s package name as the package name.

Using as to Import Under a Namespace

You can also import under a namespace, by using the following syntax:

 import​ ​'customlib.dart'​ ​as​ MyCustomLib;

So that, for example, if there is a CustomLibraryClass class defined in that file, you can access it by using MyCustomLib.CustomLibraryClass instead of just CustomLibraryClass.

This allows you to import many libraries without cluttering your main namespace, keeping each library separated, without risking having multiple classes with the same name.

Another great advantage comes when you go back to your code after a while: you will know exactly which library that class is from, without having to figure that out first.

Using show to Only Import Some Parts of a File

import can also be used to only import some classes inside a file.

For example, if you only need the CustomLibraryClass from the customlib.dart file and don’t want to import other classes (maybe because they have the same name as other classes in your namespace and you don’t want to use as and deal with extra dot notation), which you can do with the following code:

 import​ ​'customlib.dart'​ ​show​ CustomLibraryClass;
..................Content has been hidden....................

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