Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter/Dart find unused files or widgets

I am working on an existing application, it has too many unused files or widgets, I need to find all and cleanup the codes

How can I find unused files/widgets in flutter/dart environment? I am using android studio as my IDE

like image 594
WebMaster Avatar asked Dec 06 '22 08:12

WebMaster


2 Answers

Dart code metrics https://pub.dev/packages/dart_code_metrics supports finding unused files for flutter.

install:

      flutter pub add --dev dart_code_metrics

run "flutter packages get" or use your IDE to "Pub get".

run:

     flutter pub run dart_code_metrics:metrics check-unused-files lib

result:

    Unused file: lib/generated_plugin_registrant.dart
    Unused file: lib/ux/Pdf/makepdfdocument.dart
    Unused file: lib/ux/RealEstate/realestatetable.dart
...
Total unused files - 11

Howo to find unused dart or flutter files (Medium)

Introduction to dart-code-metrics (Medium)

Code-metrics can also give insight in:

  • Cyclomatic Complexity
  • Lines of Code
  • Maximum Nesting
  • Number of Methods
  • Number of Parameters
  • Source lines of Code
  • Weight of a Class
like image 152
usrisuneasy2050 Avatar answered Feb 27 '23 18:02

usrisuneasy2050


One option is also to use a bash script with find and grep. This checks if there are any files that are not imported in other files (main.dart is normally on that list, but no others should be). It may fail in some edge cases but works fine for my use case and may help you too.

The script has to be placed in the root folder of the project and all the code should be inside the lib/ directory.

I just used it to delete 15 unused files in my project and I feel lighter already :)

#!/bin/bash
  

cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1

find lib/ -name *.dart -print0 | while read -d $'\0' file
do
        name="$(basename ${file})"
        grep -rn -F -q "${name}" lib/
        if [ $? -ne 0 ]
        then
                echo "Unused file: ${file}"
        fi
done

Tested on linux but should also work on macos and bash on windows (maybe with some minor modifications (find and grep may have some other flags)).

like image 44
jaksoc Avatar answered Feb 27 '23 20:02

jaksoc