Packages, pub, and Everyday Tooling
So far, you have written programs using only the Dart language itself. Real projects rarely stop there. They reuse code that other people wrote, and they use tools to manage that code. This chapter shows how.
What is a package?
A package is a bundle of ready-made Dart code that you can add to your project. If you need to make web requests, format dates, or draw charts, someone has probably published a package for it. Packages are stored in a central online catalog called pub.dev.
What is pub?
pub is Dart's package manager. A package manager is a tool that downloads packages, keeps track of their versions, and makes sure they work together. You use it through the dart pub command.
Every Dart project has a file called pubspec.yaml. This file lists the project's name and the packages it depends on. A dependency is a package your project needs.
Here is an example pubspec.yaml:
name: my_app
environment:
sdk: ^3.0.0
dependencies:
http: ^1.2.0The line http: ^1.2.0 means "this project needs the http package, version 1.2 or later but not 2.0 or later." The caret symbol ^ sets that range.
To download the packages listed in your file, run:
dart pub getThen you can use the package in your code:
import 'package:http/http.dart' as http;
Future<void> main() async {
final response = await http.get(
Uri.parse('https://example.com'),
);
print(response.statusCode);
}What else does the tooling do?
The Dart SDK (the Software Development Kit, the toolkit that lets you build and run Dart programs) ships with a few commands you will use daily:
| Command | What it does |
|---|---|
| `dart create my_app` | Makes a new project folder with starter files |
| `dart run` | Runs your program |
| `dart analyze` | Checks your code for mistakes and style problems |
| `dart format` | Tidies up your code's spacing automatically |
| `dart pub get` | Downloads the packages your project needs |
| `dart test` | Runs your automated tests |
Two of these deserve a habit. Run dart format before you share code, so it always looks consistent. Run dart analyze often; it catches typos and type mistakes before your program ever runs.
How it fits together
Show diagram source
flowchart LR
A[pubspec.yaml] --> B[dart pub get]
B --> C[(pub.dev)]
B --> D[cached packages]
D --> E[your code imports them]Your everyday workflow
dart create my_appto start a project.- Add dependencies to
pubspec.yaml. dart pub getto fetch them.- Write code, then
dart runto try it. dart formatanddart analyzeto polish.
Exercise
What file lists the packages your project depends on, and what command downloads them?
Show answer
The pubspec.yaml file lists the dependencies, and dart pub get downloads them.
Spotted a mistake, or code that does not work?