Sub topic 4
Adding a package with flutter pub add
This chapter assumes you can run commands in a terminal, read basic YAML, and write simple Dart. It also assumes you have a Flutter project created with flutter create. You should already know that dependencies live in pubspec.yaml and that you should check a package's score, publisher, and platform support before adding it. Here you will learn what flutter pub add does, which forms of the command exist, and which errors you are most likely to meet.
What the command does
flutter pub add edits pubspec.yaml for you and then resolves dependencies. In one step it does three things:
- It asks pub.dev for the latest version of the package that is compatible with your project's SDK constraints and your other dependencies.
- It writes a dependency entry with a caret constraint into the right section of
pubspec.yaml. - It runs the equivalent of
flutter pub get, which downloads the package and updatespubspec.lock.
Run it from the project root, the folder that contains pubspec.yaml:
flutter pub add httpIf the latest version of http is 1.2.2, the command adds this line under dependencies::
dependencies:
flutter:
sdk: flutter
http: ^1.2.2The caret means "this version or any later version that is compatible", so the constraint allows 1.2.2 up to but not including 2.0.0. The next chapter covers the syntax in detail.
Command forms
The command accepts several arguments. You can combine them in one call.
Adding several packages at once
List the names separated by spaces. Pub solves them together, so a conflict between them is found in one run.
flutter pub add http provider shared_preferencesPinning a constraint
You can state a constraint yourself with a colon after the name. Quote the value if it contains characters your shell treats specially, such as < or >.
flutter pub add 'http:^1.1.0'
flutter pub add 'provider:>=6.0.0 <7.0.0'
flutter pub add http:anyUsing any removes the limit on versions. It is rarely a good idea in an app you ship, because a later major release can break your code.
Adding to a different section
By default a package goes into dependencies. Prefix the name with dev: to place it in dev_dependencies, or with override: to place it in dependency_overrides.
flutter pub add dev:build_runner
flutter pub add dev:flutter_lintsDev dependencies are packages used only while developing and testing, so they are not part of your app's runtime. A later chapter explains this section and overrides in full.
Git, path, and SDK sources
Packages do not have to come from pub.dev. The same command can add a local or git package.
flutter pub add my_local_package --path ../my_local_package
flutter pub add my_forked_package --git-url https://github.com/example/my_forked_package.git --git-ref mainBoth produce path: and git: entries like those you could write by hand.
dependencies:
my_local_package:
path: ../my_local_package
my_forked_package:
git:
url: https://github.com/example/my_forked_package.git
ref: mainPreviewing with a dry run
--dry-run shows what would change without writing anything. It is a safe way to see which version would be chosen or to test whether a package conflicts with your project.
flutter pub add http --dry-runTable of common options
| Command | Effect |
|---|---|
| `flutter pub add http` | Adds the latest compatible version to `dependencies` |
| `flutter pub add 'http:^1.1.0'` | Adds with your own constraint |
| `flutter pub add dev:build_runner` | Adds to `dev_dependencies` |
| `flutter pub add http --dry-run` | Reports the result and changes nothing |
| `flutter pub add http --offline` | Resolves using only packages already in the local cache |
| `flutter pub add foo --path ../foo` | Adds a local path dependency |
Editing pubspec.yaml by hand
The command is a convenience. You can write the same entry yourself and run flutter pub get:
dependencies:
flutter:
sdk: flutter
http: ^1.2.0
dev_dependencies:
flutter_test:
sdk: flutterManual editing is useful when you want to choose the constraint carefully, add a comment, or reorder entries. Most IDE setups with the Flutter and Dart plugins run pub get automatically when you save pubspec.yaml, but the terminal command always works.
A difference to know about: flutter pub add rewrites pubspec.yaml through a YAML editor that tries to preserve comments and formatting. It usually succeeds, but check the diff in version control after the command runs, particularly in files with unusual layout.
Using the package after adding it
Adding a package only makes it available. You still import it in Dart code. The import path starts with package:, then the package name, then the file path inside the package's lib folder.
import 'package:http/http.dart' as http;
Future<String> fetchBody() async {
final response = await http.get(Uri.parse('https://example.com'));
if (response.statusCode == 200) {
return response.body;
}
throw Exception('Request failed: ${response.statusCode}');
}The as http prefix places every name from the library under http, which avoids clashes with names from other libraries. Without the prefix, get would be a top-level function in your file's scope.
If you add http but forget the import, the analyzer reports an undefined name. If you import a package that is not in pubspec.yaml, you get a warning that the package is not a dependency (the depend_on_referenced_packages lint) and resolution can fail on other machines. Keep the two in step.
Verifying the result
After a successful add, three things should be true.
pubspec.yamlcontains the new entry in the expected section.pubspec.locklists the package, and any packages it depends on, with exact versions.dart analyze(or your IDE) accepts the import.
To see the full picture of which package pulls in which, run:
flutter pub depsThis prints a tree of direct, dev, and transitive dependencies. A transitive dependency is a package that one of your dependencies needs. You do not list those in pubspec.yaml, but they appear in the lockfile.
Common errors and how to read them
The package is not found
Could not find package "htpp" at https://pub.dev.This is almost always a typo. Check the exact name on pub.dev. Package names are lowercase with underscores.
No compatible version exists
Because my_app depends on some_package >=3.0.0 which requires SDK version >=3.4.0, version solving failed.The latest versions of the package need a newer Dart SDK than your project allows. The environment: sdk: constraint in your pubspec.yaml and the Flutter version you have installed both matter. You can upgrade Flutter, widen the project's SDK constraint if your installed SDK allows it, or ask for an older version of the package with an explicit constraint such as flutter pub add 'some_package:^2.5.0'.
Conflict with an existing dependency
Because my_app depends on both package_a ^1.0.0 and package_b ^2.0.0, and package_b requires package_a ^2.0.0, version solving failed.Two of your dependencies need incompatible versions of a shared package. flutter pub add stops and leaves your files unchanged. A later chapter on version solving shows how to read these messages and choose a fix.
Network problems
If pub cannot reach pub.dev, the command fails with a connection error. If the packages you need are already in your pub cache, --offline can resolve without the network.
The package only supports some platforms
Pub does not stop you from adding a package that lacks support for your target platform. Adding succeeds, and the failure appears later at build or run time. For example, a plugin with no web implementation throws a MissingPluginException when called in a browser. Check the platform badges on pub.dev before adding.
Which command: flutter pub or dart pub?
In a Flutter project, use flutter pub. It runs the same pub tool but uses the Dart SDK bundled with Flutter and handles Flutter-specific behavior. dart pub add works in a pure Dart project, and in a Flutter project it will refuse because the flutter SDK dependency cannot be resolved by the plain Dart tool.
Exercises
Exercise
You run flutter pub add dev:build_runner. Which section of pubspec.yaml receives the entry, and why would you choose it over a plain flutter pub add build_runner?
Show answer
The entry goes into dev_dependencies. You choose it because build_runner is a development tool for generating code and is not needed in the running app, so it should not be listed as a runtime dependency.
Exercise
You want to see which version of provider would be added to your project and whether it conflicts with your existing packages, but you do not want pubspec.yaml or pubspec.lock to change. Which command do you run?
Show answer
flutter pub add provider --dry-run. It runs the resolution and reports the outcome without writing any files.
Exercise
After flutter pub add http succeeds, your code still shows "Undefined name 'http'". What step is missing, and what line fixes it?
Show answer
The file does not import the package. Add import 'package:http/http.dart' as http; at the top of the Dart file.