Dart Cookbook
上QQ阅读APP看书,第一时间看更新

Using a library from within your app

As indicated in the previous recipe, every kind of app can contain a lib folder, which at the very least contains the model classes. These model classes are very important because they form the backbone of your project, so they must be accessible in your entire application. You can do this by placing them at the top in a lib folder, or even better in the lib/model. This central position will also make them stand out and easy to find for other readers of your code.

How to do it...

Take a look at the structure of the bank_terminal project. The model classes Person and BankAccount are placed in the lib\model folder. Give your project a name in the pubspec.yaml file:

name: bank_terminal

Then, use the same name for the library script you created in the lib folder bank_terminal.dart, which contains the following code:

library bank_terminal;

import 'dart:convert';

part 'model/bank_account.dart';
part 'model/person.dart';

Note

The library has the same name as your app! This is not required for the Dart script itself, but it is a common and advised practice.

Now when a pub get or pub upgrade command is performed, a bank_terminal folder appears in packages. You can then make this library available for use in your other Dart scripts by importing it as any hosted package you would have downloaded from the pub. For example, in web\bank_terminal.dart we have the following code:

import 'package:bank_terminal/bank_terminal.dart';

In this case, the model classes are made available. The project structure is shown in the following screenshot:

Using a library in your app

How it works...

The pub tool was designed to work this way to make it easy to use internal libraries for your app. Every script that declares a library in the lib folder (or its subfolders) will be picked up by the pub get or pub upgrade commands. The result is that the library with all its code is considered a separate "internal" package, and thus placed in the packages folder together with other packages your app depends on. This makes for a clean code model, and it also makes it easier for the pub to deploy your code.

There's more...

The pub tool can be extended to several subfolders of lib, each containing their own library file (for example, a script model.dart that starts with the library model in the model folder) and then one top-level library file project_name.dart, containing the following code as its first lines:

library project_name; 
import 'model/model.dart';   // importing library model
import 'view/view.dart';     // importing library view

…

This way, the different libraries from model, view, and so on are imported into one big library, which is then imported by the app as follows:

import 'package:project_name/project_name.dart';