Packages and pub
Prerequisites: Classes and objects
A package is a reusable bundle of Dart code. pub is Dart's package manager, and pub.dev is the public repository, with tens of thousands of packages for HTTP, state management, databases, and much more.
pubspec.yaml
Every Dart project has a pubspec.yaml describing it and its
dependencies:
name: expense_tracker
description: A small expense tracker.
version: 1.0.0
environment:
sdk: ^3.5.0
dependencies:
http: ^1.2.0
dev_dependencies:
lints: ^5.0.0
test: ^1.25.0
dependenciesare needed to run the program;dev_dependenciesonly during development (tests, lints).^1.2.0(a caret constraint) means "1.2.0 or newer, but below 2.0.0" — compatible updates without breaking changes.
Adding packages
dart pub add http
dart pub add --dev test
This updates pubspec.yaml and downloads the packages. pub records the
exact versions it chose in pubspec.lock. Commit the lock file for
apps, so everyone builds with the same versions. (In Flutter projects,
use flutter pub add.)
Importing
import 'dart:math'; // a core library
import 'package:http/http.dart' as http; // a package, with a prefix
import 'src/models.dart'; // a file in your own project
as http adds a prefix, so its names are written http.get(...) —
avoiding clashes with your own names.
Choosing packages
On pub.dev, check each package's likes, pub points (a quality score), popularity, publisher, and recent updates. Packages marked Flutter Favorite have been reviewed for quality. Every dependency is code you trust to run in your app — prefer fewer, well-maintained ones.
Common mistakes
- Editing
pubspec.yamland forgetting to rundart pub get(most editors do this automatically on save). - Adding packages for things the core libraries already do.