flutter_trim 1.2.0
flutter_trim: ^1.2.0 copied to clipboard
Interactive CLI that finds unused assets, Dart files, classes, methods and variables in Flutter projects. Click to open, delete safely, undo anytime.
flutter_trim ✂️ #
An interactive command-line tool that finds unused assets, unreferenced Dart files and unused classes, functions, methods and variables in a Flutter project, then walks you through them one by one so you can Keep or Delete each one.
╭─ Class ────────────────────────────────────────────────── 12 / 21 ─╮
│ PromoBannerV1 │
│ lib/widgets/promo_banner_v1.dart:14 · 2.3 KB │
│ No references outside its own declaration │
├────────────────────────────────────────────────────────────────────┤
│ 14 │ class PromoBannerV1 extends StatelessWidget { │
│ 15 │ const PromoBannerV1({super.key, required this.offer}); │
│ 16 │ │
│ 17 │ final Offer offer; │
╰────────────────────────────────────────────────────────────────────╯
▰▰▰▰▰▰▰▰▰▰▰▱▱▱▱▱▱▱▱▱ 4 deleted · 7 kept
? What do you want to do?
❯ Keep
Delete
Delete all remaining
Undo last delete (OldPromoCard)
Quit and keep the rest
✨ What's new #
| 🔗 Click to open the code (1.2) | Every path in the report and on each card is clickable and opens the file at the right line: in the VS Code, Cursor and Android Studio terminals, and in iTerm2, WezTerm, kitty, Ghostty and Windows Terminal. |
| 🧮 Unused variables and fields (1.2) | Top-level variables/constants and class fields (instance and static) that nothing reads or writes are now found and can be removed. |
| ↺ Undo last delete (1.1) | Changed your mind during the review? Pick it from the menu and the last deleted item is back. Pick it again to go further back. |
🛟 ftrim --restore (1.1) |
Brings back everything deleted in your last session, even after ftrim has exited. |
| 💾 Automatic backups (1.1) | Originals are saved to .flutter_trim/backups/ before anything is touched. If a backup fails, nothing is deleted. |
See the changelog for details.
Formerly published as
flutter_sweeper. The package was renamed and its import resolution rewritten for large projects.
Features #
🔍 What it finds #
- Unused assets. Reads
flutter: assets:frompubspec.yaml, expands directory entries the way Flutter does (including2.0x/and3.0x/variants), also finds files inassets/that were never declared, and checks them against every Dart source plus tool configs such asflutter_launcher_icons. Projects using flutter_gen are matched by getter name (Assets.images.logo). - Unreferenced Dart files. Builds an import graph from your entry points
(
main*.dart,test/,bin/, ...) throughimport,export,partand conditional imports. Files that cannot be reached are reported, and theirpartfiles (*.g.dart,*.freezed.dart) are deleted with them. - Unused classes, mixins, enums, typedefs, functions and methods. Uses the
official
analyzerAST instead of regular expressions, so comments, strings and self references do not confuse it. - Unused variables and fields. Top-level variables and constants, and
class fields (instance and
static), that are never read, written or initialized anywhere. A field set throughthis.xor an initializer list counts as used;@overridefields andint a, b;style declarations are never reported. Turn it off with--no-variables.
🔗 Jump straight to the code #
Every location (lib/home/home_screen.dart:42) is clickable and opens the
file at that line. VS Code, Cursor and Android Studio / IntelliJ terminals
work out of the box. In other terminals ftrim adds a hyperlink (Cmd/Ctrl +
click): choose where it opens with --editor vscode|cursor|idea|file, or
turn links off with --editor none.
🛡️ Safe by design #
- You decide. Every finding is shown as a card with a code preview.
Choose Keep, Delete, Delete all remaining or Quit. Nothing is deleted
without your choice, and
--dry-runonly prints the report. - Undo anytime. Everything is backed up before it is deleted. Undo the
last delete during the review, or bring back a whole session with
ftrim --restore. - Never breaks a file. Declarations are cut out together with their doc comments and annotations, and the file is parsed again before anything is written. If the edit would add a syntax error, the file is left untouched.
- Conservative. When in doubt, an item is treated as used. Generated
code is never reported,
@pragma/@protectedcode and// flutter_trim:keepare respected.
🚀 Built for real projects #
- Large apps. Tested on production Flutter apps with 400–600 Dart
files: 0 false positives across 134 findings. Import paths with spaces
(
common%20widget/) and imports whose letter case differs from the file name (which macOS and Windows accept) are resolved correctly. - No setup. Pure Dart. No Flutter SDK or
pub getneeded in the target project. An optionalflutter_trim.yamlcovers excludes and entry points. - CI ready.
--jsonfor machine-readable output and--fail-on-findingsto fail a build when something is unused.
Installation #
dart pub global activate flutter_trim
Make sure the pub cache bin folder is on your PATH, then use either
executable:
ftrim --help
flutter_trim --help
Usage #
Run it from the root of a Flutter project (the folder with pubspec.yaml):
ftrim # interactive review
ftrim --dry-run # report only, nothing is deleted
ftrim --assets-only # only assets
ftrim --code-only # only Dart files and declarations
ftrim --code-only --no-methods # skip method-level findings
ftrim -p ../other_app # scan another project
ftrim -e "lib/legacy/**" -e "assets/legal/**"
ftrim --json > report.json # machine-readable report
ftrim -n --fail-on-findings # exit code 1 if anything is unused
ftrim --restore # undo the deletions of the last session
| Option | Abbr | Description |
|---|---|---|
--path <dir> |
-p |
Project root to scan (default: current folder). |
--assets-only |
Only look for unused assets. | |
--code-only |
Only look for unused Dart files and declarations. | |
--dry-run |
-n |
Print the report and exit without deleting. |
--exclude <glob> |
-e |
Never report matching paths. Repeatable. |
--[no-]methods |
Report unused methods inside used classes (default on). | |
--[no-]variables |
Report unused top-level variables and class fields (default on). | |
--editor <name> |
Where clickable paths open: auto (default), vscode, cursor, idea, file or none. |
|
--json |
Print the findings as JSON (implies --dry-run). |
|
--fail-on-findings |
Exit with code 1 when anything unused is found. | |
--[no-]backup |
Back up everything before deleting it, so it can be undone (default on). | |
--restore |
Bring back everything deleted in the most recent session, then exit. Run it again to undo older sessions. | |
--verbose |
-v |
Diagnostic output. |
--version |
Print the version. | |
--help |
-h |
Show usage. |
Interactive choices #
| Choice | Effect |
|---|---|
| Keep | Leave the item and move on to the next one. |
| Delete | Delete the file or remove the declaration now. |
| Delete all remaining | After a confirmation, delete this and every remaining item. |
| Undo last delete | Put back the item deleted most recently (shown once something was deleted). It then counts as kept. |
| Quit and keep the rest | Stop and leave everything that is left. |
Undo and restore #
Before a file is deleted or a declaration is removed, flutter_trim copies
the original into .flutter_trim/backups/<session>/ in the project root.
Each deletion can be undone during the review with Undo last delete, and
ftrim --restore brings back every deletion of the most recent session,
newest first. Add .flutter_trim/ to your .gitignore. Delete that folder
when you no longer need the backups. Pass --no-backup to skip backups.
When the terminal is not interactive (CI, piped output), flutter_trim only prints the report.
JSON output #
{
"tool": "flutter_trim",
"version": "1.0.0",
"project": "/path/to/app",
"summary": { "total": 3, "sizeBytes": 4210, "asset": 1, "file": 1, "declaration": 1 },
"items": [
{ "type": "declaration", "kind": "method", "name": "voteBlog", "parent": "AppUrl",
"path": "lib/core/network/api_url.dart", "line": 188, "sizeBytes": 83,
"reason": "Method is never called or torn off anywhere in the project" }
]
}
Configuration #
Create an optional flutter_trim.yaml next to pubspec.yaml:
# Paths that are never reported (globs, relative to the project root).
exclude:
- lib/generated/**
- assets/legal/**
# Extra entry points for the import graph (flavors, isolates, ...).
entry_points:
- lib/bootstrap/background_worker.dart
# Declarations that must never be reported.
keep:
- LegacyApiClient
- onDidReceiveBackgroundNotification
# Folders searched for assets in addition to pubspec declarations.
asset_directories:
- assets
- res
# Turn whole scanners on or off.
scan:
assets: true
files: true
code: true
methods: true
variables: true
CLI --exclude globs are added to the ones in the config file, and
--[no-]methods overrides scan.methods, --[no-]variables overrides
scan.variables.
Protecting code inline #
// flutter_trim:keep
void calledFromNativeSide() {}
@pragma('vm:entry-point') // Also protected automatically.
void backgroundHandler() {}
Declarations annotated with @protected are never reported either.
Put // flutter_trim:ignore_file anywhere in a file to exclude all of its
declarations, and the file itself, from the report.
How it works #
- Parse once. Every
.dartfile inlib/,test/,bin/,tool/,integration_test/andtest_driver/is parsed withpackage:analyzer. Files with invalid UTF-8 are still read, so their references are never lost. - Assets. Each candidate counts as used when its full path, its file name or its flutter_gen getter appears in a Dart source or a config value.
- Files. A breadth-first walk follows
import/export/part(including conditional imports) from the entry points. URIs are percent-decoded and matched to files case-insensitively when there is no exact match. Packages without amaintreat every public library directly underlib/as an entry point. - Declarations. For each class, mixin, enum, typedef, top-level function
and method in reportable
lib/files, flutter_trim looks for the name among the identifier tokens of all project files, ignoring occurrences inside the declaration itself.
Generated files (*.g.dart, *.freezed.dart, *.gr.dart, *.config.dart,
*.mocks.dart, *.gen.dart, protobuf output, app_localizations*.dart,
lib/generated/**) are never reported. They still count as references.
Limitations #
flutter_trim is conservative: when in doubt it treats something as used. Keep these cases in mind:
- Name-based matching. Two declarations with the same name keep each other alive, and a method name used anywhere (even on an unrelated type) counts as used.
- Dynamic asset paths such as
'assets/icons/$name.png'cannot be resolved. The file-name check catches'$dir/logo.png', but not names built at runtime. - Hand-written asset constant files (
static const logo = 'assets/...') make every listed asset look used, even if the constant is not. - Code used only by tests counts as used.
- Reflection,
dart:mirrors, platform channels and native callbacks are invisible to static analysis. Protect them with@pragma('vm:entry-point'),// flutter_trim:keepor thekeep:list. - Published packages. Public API under
lib/may be used by other packages. Review findings carefully, or excludelib/and only trimlib/src/.
Recommended workflow #
git status # start from a clean working tree
ftrim --dry-run # look at the report first
ftrim # review and delete
dart fix --apply # remove imports that became unused
flutter analyze && flutter test
git diff # review, then commit
flutter_trim warns you before it deletes anything in a project that is not under git.
Programmatic use #
import 'package:flutter_trim/flutter_trim.dart';
void main() {
final context = ProjectContext.load('path/to/app');
final unusedFiles = FileScanner(context).scan();
final unusedCode = CodeScanner(
context,
skipFiles: {for (final item in unusedFiles) item.path},
).scan();
for (final item in [...AssetScanner(context).scan(), ...unusedFiles, ...unusedCode]) {
print('${item.typeLabel.padRight(10)} ${item.location} ${formatBytes(item.sizeBytes)}');
}
}
Contributing #
Issues and pull requests are welcome, especially reports of false positives. See CONTRIBUTING.md for the development setup and checks to run before opening a PR.
License #
MIT. See LICENSE.