Sub topic 11
Removing a Package Cleanly
This chapter assumes you can add a package with flutter pub add, that you know what pubspec.yaml and pubspec.lock are, and that you can read a Dart import. Removing a package takes one command. Removing it cleanly also means deleting the code that used it, understanding what happens to the lockfile and to transitive dependencies, and clearing out any platform setup the package needed.
What "clean" means
A package can leave traces in several places:
- The entry in
pubspec.yaml. - The resolved entry in
pubspec.lock, plus any transitive packages only it needed. importlines and calls in your Dart files.- Generated files, if the package was a code generator.
- Platform configuration, if the package was a plugin.
- Assets or configuration blocks in
pubspec.yamlthat belonged to the package.
If you miss any of these, the project may fail to compile, build with dead weight, or carry stale permissions.
Step 1: Find where the package is used
Before you remove anything, find every file that imports the package. A search for the package URI works well:
grep -rn "package:http/" lib test integration_testIf you removed the dependency first, the analyzer would report each of these imports as an error. That also works as a to-do list, but searching first lets you plan a replacement. Check test and integration_test too, because test files often import packages that lib does not.
Also check for indirect use. If your code imports package:meta/meta.dart but you never listed meta in pubspec.yaml, it only worked because another package pulled it in. The depend_on_referenced_packages lint warns about this. Removing the package that brought it in will break that import. The fix is to add the package you actually use as a direct dependency.
Step 2: Remove the dependency
Use the pub tool:
flutter pub remove httpThis command does three things:
- Deletes the
httpline frompubspec.yaml. - Re-resolves the dependency graph.
- Updates
pubspec.lockand the package configuration used by the analyzer and build.
It finds the package in whichever section holds it. That can be dependencies, dev_dependencies, or dependency_overrides. To remove a package that is only in dev dependencies, name it with the dev: prefix:
flutter pub remove dev:build_runnerYou can remove several packages in one call. Pub resolves once at the end, which is faster and avoids intermediate states that fail to resolve:
flutter pub remove http intlYou can also edit pubspec.yaml by hand and run flutter pub get. The result is the same. The command form is less error-prone because YAML indentation mistakes are easy to make.
Step 3: Delete or replace the code
After the dependency is gone, the project will not compile until you remove the imports and calls. Run the analyzer:
flutter analyzeTypical output after removing http looks like this:
error • Target of URI doesn't exist: 'package:http/http.dart' • lib/data/api.dart:1:8 • uri_does_not_exist
error • Undefined name 'http' • lib/data/api.dart:4:24 • undefined_identifierWork through each error. If you are replacing the package with another one, add the new package first and migrate the call sites. For example, here is a function that used http and now uses dart:io, which needs no dependency:
import 'dart:convert';
import 'dart:io';
Future<String> fetchBody(Uri uri) async {
final client = HttpClient();
try {
final request = await client.getUrl(uri);
final response = await request.close();
if (response.statusCode == 200) {
return await response.transform(utf8.decoder).join();
}
throw Exception('Request failed: ${response.statusCode}');
} finally {
client.close();
}
}This version works on mobile and desktop. dart:io is not available on the web, so a web target needs a different approach. Check your supported platforms before you swap in a core-library replacement.
What happens to the lockfile
pubspec.lock records the exact version of every package in the resolved graph, direct and transitive. When you remove a package, pub recomputes the graph. Packages that no other dependency needs are dropped from the lockfile.
Packages that something else still needs stay. They also stay at their locked version. Pub does not upgrade them just because a neighbor left.
| Situation | Effect on `pubspec.lock` |
|---|---|
| Package used only by the removed package | Its entry is deleted |
| Package also used by another dependency | The entry stays, at the same version |
| Package you also list directly | The entry stays, marked as a direct dependency |
| Removed package was the only one holding a transitive package at an old version | The entry stays at the locked version until you run `flutter pub upgrade` |
The last row is a common surprise. Constraints from the removed package no longer apply, so newer versions of other packages may now be allowed. Pub will not take them until you ask. If you want that, run:
flutter pub outdated
flutter pub upgradeCommit pubspec.yaml and pubspec.lock together. For an app, the lockfile belongs in version control so that every machine builds with the same versions. A change to one without the other makes the history confusing.
Check what remains
To confirm that a package is really gone, including transitively, use the dependency tree:
flutter pub depsTo see why a particular package is still in the graph, ask for the full tree and search it:
flutter pub deps --style=compact | grep -n "path_provider"If a package you thought you removed still appears, some other dependency requires it. You cannot remove it without removing or replacing that dependency. This is normal and not a sign that the removal failed.
Removing plugins: platform leftovers
A plugin is a package with native code for Android, iOS, web, or desktop. Flutter regenerates the files that register plugins, such as GeneratedPluginRegistrant, from the lockfile. When a plugin leaves the lockfile, those registrations are rebuilt without it on the next run or build. You do not edit generated files by hand.
Files you wrote yourself are not cleaned up. Look for these:
- Android: permissions added to
android/app/src/main/AndroidManifest.xml, such asCAMERAorACCESS_FINE_LOCATION. Also checkbuild.gradlechanges, like a raisedminSdk, and any ProGuard rules. - iOS: usage description keys in
ios/Runner/Info.plist, such asNSCameraUsageDescription. Also checkPodfilechanges, and capabilities enabled in Xcode. - Web:
<script>tags added toweb/index.html. - Any platform: API keys or configuration files, for example a Firebase config file.
Removing permissions you no longer need matters. Unused permissions show up in store listings and review, and users see them in the install prompt. Keep a permission only if another plugin still needs it.
After you clean up, rebuild from scratch so stale native build output does not hide a problem:
flutter clean
flutter pub get
flutter runOn iOS, flutter clean followed by a fresh build also regenerates the CocoaPods setup, so the removed plugin's pod is not linked.
Removing code generators and dev dependencies
If you remove a code generation package such as json_serializable, you usually need to remove three things: the dev dependency on build_runner, the annotation package in dependencies, and the generated files, which typically end in .g.dart.
flutter pub remove json_annotation dev:json_serializable dev:build_runnerGenerated files stay on disk. They are often listed in .gitignore or committed, depending on your team's convention. Delete them, and remove part 'file.g.dart'; lines from the source files that referenced them. Otherwise the analyzer will report missing parts or unresolved imports.
Some packages also read configuration from files such as build.yaml or analysis_options.yaml. For example, if you remove flutter_lints but analysis_options.yaml still has include: package:flutter_lints/flutter.yaml, the analyzer will report that the included file cannot be found. Remove that line too.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Target of URI doesn't exist: 'package:x/x.dart'` | An import of the removed package remains | Delete the import and migrate its usage |
| `Could not find package x` after a manual edit | `pubspec.yaml` was edited but `pub get` was not run | Run `flutter pub get` |
| Removal reports the package is not a dependency | It is only a transitive dependency, or the name is misspelled | Check `flutter pub deps` for the real parent |
| Another package breaks after the removal | You imported it without listing it directly | Add it as a direct dependency |
| Old permissions remain in the built app | Platform files were not edited | Edit the manifest or plist by hand, then run `flutter clean` |
| `Included file ... can't be found` in the analyzer | `analysis_options.yaml` still includes the removed package | Remove the `include:` line |
A full worked example
Suppose you want to remove shared_preferences from an app and replace it with a file written through dart:io. Follow this order:
- Search for usages:
grep -rn "shared_preferences" lib test. - Replace each call site with your new storage code and delete the import lines.
- Remove the dependency:
flutter pub remove shared_preferences. - Run
flutter analyzeand fix any remaining errors. - Run
flutter testto confirm behavior is unchanged. - Run
flutter clean, thenflutter runon each platform you ship to. - Review
git diffto confirm that onlypubspec.yaml,pubspec.lock, and your intended source files changed.
If step 7 shows lockfile changes for packages unrelated to the one you removed, check flutter pub deps before committing. That can happen when the lockfile was out of date before you started. Keep such changes in a separate commit so the removal stays easy to review and revert.
Exercise
You run flutter pub remove image_picker in an app. The analyzer is clean, but a teammate points out that the app's iOS build still prompts users for camera access and the Android manifest still declares CAMERA. Why did pub remove not delete these, and what should you do?
Show answer
pub remove only edits pubspec.yaml and the resolved dependency graph. The permission entries in ios/Runner/Info.plist (such as NSCameraUsageDescription) and android/app/src/main/AndroidManifest.xml were written by hand and are not managed by pub. First search the app's own code and the remaining plugins for any other camera use. If none exists, delete those entries manually, then run flutter clean and rebuild on both platforms.
Exercise
After flutter pub remove dio, flutter pub deps still lists http_parser. Does this mean the removal failed? How can you find out why it is still there?
Show answer
No. http_parser is a transitive package, so it stays whenever another dependency still requires it, such as http. Run flutter pub deps and look for which package lists http_parser beneath it. If nothing in your project needs it, it would disappear from pubspec.lock on the next resolution.