Sub topic 12
Adding a package
This chapter covers how Flutter projects pull in third-party code. You will add the http package, read what the command changes, and learn how to fix the usual failures. It assumes you have a working project from flutter create, a terminal in the project folder, and a basic idea of what pubspec.yaml is from the project tour.
What a package is
A package is a versioned bundle of Dart code, published on pub.dev, the public package repository for Dart and Flutter. Your app declares which packages it needs. A tool called pub (built into both the dart and flutter commands) downloads them and tells the compiler where to find them.
Packages come in two broad kinds:
- A Dart package contains only Dart code, such as
httporcollection. It works on every platform Dart supports. - A plugin package contains Dart code plus platform-specific code in Kotlin, Swift, C++, or JavaScript. Examples are packages for the camera or local storage. Flutter builds the native part into your app.
The difference matters when you iterate. Changes to Dart-only dependencies are picked up quickly. A newly added plugin needs a full rebuild, as described later in this chapter.
Adding a dependency
From the project root, run:
flutter pub add http
flutter pub getflutter pub add does three things:
- It finds the latest version of
httpthat is compatible with your SDK and your other dependencies. - It writes a line for it under
dependencies:inpubspec.yaml. - It runs
flutter pub get, which downloads the package and its own dependencies.
Because pub add already runs pub get, the second command is redundant here. You still need flutter pub get after editing pubspec.yaml by hand, after pulling a teammate's changes, or after cloning a project.
Your pubspec.yaml now contains something like this. The version number will differ depending on when you run the command.
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.8
http: ^1.2.2Reading version constraints
The ^1.2.2 is a caret constraint. It means "any version from 1.2.2 up to, but not including, 2.0.0". Dart packages follow semantic versioning, so a major version bump signals breaking changes. The caret lets you receive bug fixes and new features without accepting breaking ones.
| Constraint | Meaning |
|---|---|
| `^1.2.2` | At least 1.2.2 and below 2.0.0 |
| `">=1.2.0 <1.5.0"` | An explicit range |
| `1.2.2` | Exactly this version |
| `any` | No restriction (avoid this) |
To request a specific constraint from the command line, append it to the name:
flutter pub add http:^1.2.0What pub changes on disk
Running pub get touches three places. Knowing them helps when something looks wrong.
pubspec.yamlholds the constraints you wrote. You edit this file, and you commit it.pubspec.lockholds the exact versions pub resolved, including indirect dependencies. For an application, commit this file so everyone builds with identical versions. Library authors usually leave it out of version control.- The pub cache is a shared folder on your machine (
~/.pub-cacheon macOS and Linux,%LOCALAPPDATA%\Pub\Cacheon Windows). Downloaded packages live here once and are reused across projects.
Pub also writes tooling metadata under .dart_tool/, including package_config.json. That file maps each package name to a folder, and it is how import 'package:http/http.dart' finds the code. You should not edit it or commit it.
Using the package
A package is not available in a file until you import it. Here is a small function that fetches a page and returns its status code:
import 'package:http/http.dart' as http;
Future<int> fetchStatus(String url) async {
final response = await http.get(Uri.parse(url));
return response.statusCode;
}
Future<void> main() async {
final status = await fetchStatus('https://example.com');
print('Status: $status');
}Three details are worth noting:
- The
as httpprefix keeps the package's names (get,post,Client) from colliding with your own. http.gettakes aUri, not aString. Passing a plain string is a compile error. UseUri.parse, orUri.https('example.com', '/path')when you want the pieces built safely.- The call is asynchronous. It returns a
Future, so you mustawaitit or use.then.
You can save this as a file in lib/ and run it from the project root with dart run lib/your_file.dart. Inside a real app you would call fetchStatus from a widget, for example in initState, and store the result in state with setState.
Network permissions on device
Importing http is not enough on every platform. Release builds on Android need the internet permission in android/app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />Place it as a child of the <manifest> element, above <application>. Debug builds include this permission already, which is why a request can work in development and then fail in a release build. On macOS, sandboxed apps need the com.apple.security.network.client entitlement in both macos/Runner/DebugProfile.entitlements and macos/Runner/Release.entitlements.
Dependency types
Not every package belongs under dependencies:. Pub supports separate sections:
dependencies:lists packages your app code imports fromlib/. They are shipped with the app.dev_dependencies:lists tools used only during development, such asflutter_test,flutter_lints, orbuild_runner. They are not part of the app.dependency_overrides:forces a specific version and ignores other packages' constraints. Use it as a temporary workaround only.
To add a development-only package, prefix the name with dev::
flutter pub add dev:flutter_lintsPutting a testing or code generation tool under dependencies: is a common beginner mistake. It does not break the build, but it adds weight and signals the wrong intent.
Managing packages over time
These commands cover most day-to-day maintenance:
flutter pub remove http
flutter pub outdated
flutter pub upgrade
flutter pub depspub removedeletes the line frompubspec.yamland re-resolves.pub outdatedprints a table of current, upgradable, and latest versions for each package, which shows what the caret constraints are holding back.pub upgrademovespubspec.lockto the newest versions your constraints allow. It does not changepubspec.yaml.pub depsprints the full dependency tree, useful for finding where an unexpected indirect package came from.
When you want to cross a major version, run flutter pub upgrade --major-versions. It rewrites the constraints in pubspec.yaml, so read the package's changelog first.
Choosing a package
Pub.dev shows signals to help you judge a package before adding it:
- Pub points measure how well the package follows Dart conventions, such as documentation and platform support.
- Popularity and likes show how widely it is used.
- The platform tags show which targets it supports. A package that lacks the web tag will fail on a web build.
- The "Verified publisher" badge shows that the publisher has proven control of a domain.
- The repository link, issue tracker, and date of the last release show whether anyone maintains it.
Prefer packages published by the Dart or Flutter teams when they cover your need, and check that the license suits your project.
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| `Target of URI doesn't exist: 'package:http/http.dart'` | Dependencies not fetched, or the package is not declared | Run `flutter pub get` and check `pubspec.yaml` |
| `version solving failed` | Two packages require incompatible versions of a third | Read the message to find the conflict, loosen a constraint, or upgrade the older package |
| `The current Dart SDK version is X` | The package needs a newer SDK than you have | Run `flutter upgrade`, or pick an older package version |
| `Error on line N, column M` in `pubspec.yaml` | Bad YAML indentation | Use two spaces per level and no tabs |
| `MissingPluginException` after adding a plugin | Native code was not rebuilt | Stop the app and run `flutter run` again |
Hot reload and new packages
Hot reload injects changed Dart code into the running app. It cannot add native code. After adding a plugin, stop the app and start it again with flutter run. Even for a Dart-only package, a hot restart is the safer choice the first time you use it, because the app's compiled state has to include the new import.
Exercise
You add flutter_lints with flutter pub add flutter_lints, and the app builds. A teammate says it should not be listed under dependencies:. Which command puts it in the right section, and why does the section matter?
Show answer
Use flutter pub add dev:flutter_lints (or move the line under dev_dependencies: in pubspec.yaml and run flutter pub get). Lint rules are only used while developing, so they belong in dev_dependencies:. That section is not shipped with the app and states clearly that no code in lib/ should import the package.
Exercise
Your app fetches data with http.get and works under flutter run. After flutter run --release on an Android device, every request fails. What do you check first?
Show answer
Check that android/app/src/main/AndroidManifest.xml declares <uses-permission android:name="android.permission.INTERNET" />. Debug builds add this permission automatically, so the missing declaration only shows up in release builds.