Dart Package and Library Management
As a project grows, splitting code into multiple files and modules becomes essential.
This chapter introduces Dart's package management system pub, the dependency configuration file pubspec.yaml, import/export syntax, and how to create custom libraries.
pubspec.yaml configuration
pubspec.yaml is the core configuration file of every Dart project, declaring the project's metadata and dependencies.
A typical pubspec.yaml file structure is as follows:
Example
File path: pubspec.yaml
name
:
my_dart_app
Project name (required, lowercase + underscores)
description
:
A Dart sample project
Project description
version
:
1.0.0
Version number
publish_to: none # If you don't want to publish to pub.dev, uncomment this line
environment
:
sdk
:
'>=3.0.0 <4.0.0'
Dart SDK version range
dependencies
:
Third-party packages that the project depends on at runtime
http
:
^1.1.0
HTTP client
path
:
^1.8.0
Path utilities
dev_dependencies
:
Dependencies needed only during development (testing, code linting, etc.)
test
:
^1.24.0
Test framework
lints
:
^2.0.0
Official lint rules
Optional: executable entry point
executables:
my_app: main
Notes on how to write version numbers:
| Syntax | Meaning | Example |
|---|---|---|
| ^1.1.0 | Compatible with 1.1.0 up to 2.0.0 (exclusive) | Most common, recommended |
| 1.1.0 | Exact version | Not very flexible |
| >=1.1.0 <1.5.0 | Version range | Used when precise control is needed |
| any | Any version | Not recommended |
The ^ symbol (caret) is Dart's default version constraint. ^1.1.0 is equivalent to >=1.1.0 <2.0.0. This means minor and patch versions can be upgraded automatically, but major versions cannot (a major version upgrade may contain breaking changes).
Install dependencies
$ dart pub get # 安装依赖
$ dart pub upgrade # 升级依赖到最新兼容版本
$ dart pub outdated # 查看哪些依赖有更新
Finding dependencies on pub.dev
pub.dev is the official package repository for Dart and Flutter, similar to npm (JavaScript) or PyPI (Python).
You can https://pub.dev Search and browse tens of thousands of Dart packages on it.
Examples of commonly used third-party packages:
| Package name | Purpose | Description |
|---|---|---|
| http | HTTP request | Officially maintained HTTP client |
| path | Path operations | Cross-platform path handling utility |
| test | Unit testing | Official testing framework |
| json_serializable | JSON serialization | Automatically generate JSON conversion code |
| dio | HTTP client | A third-party HTTP library more powerful than http |
| riverpod | State management | A popular state management solution for Flutter projects |
Example
Add the http package and use it:
// First, add it to dependencies in pubspec.yaml:
// http: ^1.1.0
// Then run: dart pub get
import
'package:http/http.dart'
as
http
;
void
main
(
)
async
{
// Send a GET request
var
url
=
Uri.
parse
(
'https://www.runoob.com'
)
;
var
response
=
await http.
get
(
url
)
;
(
'Status code: ${response.statusCode}'
)
;
(
'Response body length: ${response.body.length} characters'
)
;
}
import syntax
import is used to bring code from other libraries into a Dart file.
Dart supports multiple import styles, each suited to different scenarios.
Importing Dart built-in libraries
Example
// The dart: prefix denotes Dart's built-in core libraries
import
'dart:math'
;
// Math library (random numbers, trigonometric functions, etc.)
import
'dart:convert'
;
// Encoding conversion library (JSON, Base64, etc.)
import
'dart:io'
;
// I/O library (files, network, etc.)
void
main
(
)
{
// Use functions from dart:math
(
'Pi: $pi'
)
;
(
'2 to the power of 10: ${pow(2, 10)}'
)
;
// Use functions from dart:convert
var
jsonStr
=
'{"name": "runoob", "age": 10}'
;
var
decoded
=
jsonDecode
(
jsonStr
)
;
(
'Parsed JSON: $decoded'
)
;
(
'Username: ${decoded['
name
']}'
)
;
}
圆周率: 3.141592653589793
2 的 10 次方: 1024
解析后的 JSON: {name: runoob, age: 10}
用户名: runoob
Importing third-party packages
Example
// The package: prefix denotes third-party packages on pub.dev
import
'package:http/http.dart'
;
import
'package:path/path.dart'
as
p
;
Importing local files
Example
// Relative path import: import other Dart files in the same project
import
'src/utils.dart'
;
// A subdirectory under the same directory
import
'../models/user.dart'
;
// A file in the parent directory
import
'constants.dart'
;
// A file in the same directory
Modifiers for import
| Modifiers | Syntax | Purpose |
|---|---|---|
| Prefix (as) | import 'lib.dart' as myLib; | Give a library an alias to avoid naming conflicts |
| Import only part (show) | import 'lib.dart' show foo, bar; | Import only specified names |
| Exclude part (hide) | import 'lib.dart' hide foo; | Import everything except the specified names |
| Deferred loading (deferred as) | import 'lib.dart' deferred as lib; | Load on demand to reduce startup time |
Example
Practical usage of the various import modifiers:
import
'dart:math'
;
// Standard import
import
'dart:math'
as
math
;
// Prefix import: use math.pow() instead of pow()
import
'dart:math'
show pi
,
sqrt
;
// Import only pi and sqrt
import
'dart:math'
hide Random
;
// Import everything except Random
void
main
(
)
{
// Standard import
(
'sin(0) = ${sin(0)}'
)
;
// Prefix import: must access through the prefix
(
'cos(0) = ${math.cos(0)}'
)
;
// show import: only pi and sqrt can be used
(
'π = $pi'
)
;
(
'sqrt(16) = ${sqrt(16)}'
)
;
// print(sin(0)); // Error: sin was not imported
// hide import: Random is unavailable, everything else is available
(
'max(3, 7) = ${max(3, 7)}'
)
;
// Random(); // Error: Random was excluded
}
sin(0) = 0.0
cos(0) = 1.0
π = 3.141592653589793
sqrt(16) = 4.0
max(3, 7) = 7
show and hide are not just for convenience -- they are also code quality tools. Using show makes dependencies clearer: you can see at a glance which symbols from a library this file uses.
export syntax
export is used to re-expose the public API of other libraries, mainly for creating aggregate libraries.
Suppose you have the following file structure:
lib/
├── my_package.dart # 入口文件(聚合导出)
├── src/
│ ├── models/
│ │ └── user.dart # User 类
│ ├── services/
│ │ └── api_service.dart # API 服务
│ └── utils/
│ └── helpers.dart # 工具函数
Example
Use export to create an aggregate library entry point:
// File: lib/my_package.dart
// Aggregate export: expose all public APIs uniformly
export
'src/models/user.dart'
;
export
'src/services/api_service.dart'
;
// Export only part of the content in helpers
export
'src/utils/helpers.dart'
show formatDate
,
validateEmail
;
This way users only need to import a single file:
Example
// Users only need to import the entry file
import
'package:my_package/my_package.dart'
;
void
main
(
)
{
// All exported classes can be used directly
var
user
=
User
(
'runoob'
)
;
var
api
=
ApiService
(
)
;
}
Creating custom libraries
Creating a custom library requires no special syntax -- every Dart file is a library.
But you can use the library keyword to explicitly declare a library name, and use part/part of to split large libraries.
Using library to declare a library name
Example
// File: lib/calculator.dart
// library declares the library name (optional, but helpful for documentation)
library
calculator
;
/// Addition operation
int
add
(
int
a
,
int
b
)
=>
a
b
;
/// Subtraction operation
int
subtract
(
int
a
,
int
b
)
=>
a
b
;
/// Multiplication operation
int
multiply
(
int
a
,
int
b
)
=>
a
b
;
/// Division operation, throws an exception when the divisor is 0
double
divide
(
int
a
,
int
b
)
{
if
(
b
==
0
)
{
throw
ArgumentError
(
'Divisor cannot be 0'
)
;
}
return
a
/
b
;
}
Using part to split large libraries
When a library's code gets too long, you can use part to split it into multiple physical files, but they still logically belong to the same library.
Example
The main file declares part:
// File: lib/user_system.dart
// Main library file
library
user_system
;
// Declare the other files that make up this library
part
'src/user_model.dart'
;
part
'src/user_service.dart'
;
part
'src/user_validator.dart'
;
// Library-level public API
String libraryVersion
=
'1.0.0'
;
Example
The part file declares part of:
// File: lib/src/user_model.dart
// part of declares which library it belongs to
part
of
'../user_system.dart'
;
// Can access libraryVersion in the main library
class
User
{
String name
;
User
(
this
.
name
)
;
void
printVersion
(
)
{
(
'RUNOOB User module version: $libraryVersion'
)
;
}
}
part/part of is rarely used in modern Dart development; most teams prefer import/export to organize code. The downside of part is that part files share all private members, breaking encapsulation. Unless there is a clear need, import/export is recommended.
A quick look at Dart core libraries
| Library name | Import method | Main Function |
|---|---|---|
| dart:core | Automatically imported | Basic types, collections, exceptions, etc. |
| dart:math | import 'dart:math'; | Math constants and functions |
| dart:convert | import 'dart:convert'; | JSON, UTF-8, Base64 encoding/decoding |
| dart:io | import 'dart:io'; | File, network, and process operations |
| dart:async | import 'dart:async'; | Async tools such as Future and Stream |
| dart:collection | import 'dart:collection'; | More collection types (Queue, etc.) |
| dart:developer | import 'dart:developer'; | Debugging and performance profiling tools |
dart:core is automatically imported; you don't need to write import 'dart:core' to use basic types like int, String, List, and Map.