A clean project following conventions is way better than a crappy project containing yolo code. In Dart and Flutter, everything is already available to make your life easier.
Formatter
A formatter is already present with the Dart SDK. The command dart format will do the job. If one wants to see only the modification without applying them:
$ dart format show
The dart format is a shortcut for dart format write, meaning it will apply all changes by default.
$ dart format write
More information can be available here:
Dart Format from the official Dart Documentation;
Flutter Formatting from the official Flutter documentation
Dart Style FAQ from the Official Dart Wiki.
Analyzer
An analyzer is also present by default with the SDK. The command dart analyze will analyze the code and print all potentials issues to fix.
$ dart analyze
The same command is available with Flutter, only the output will change a bit.
$ flutter analyze
More information can be found there:
Dart Analyze from the Official Dart Documentation;
Dart Analyzer Package on pub.dev;
Dart Analyze Source Code from the official Dart Github Repository.
Auto Fix
It's also possible to auto-fix the issues by using the dart fix command. It was never a good idea to apply those kind of commands in the past, and to be honest, I am not a big fan of that, but here how to use them anyway:
$ dart fix --dry-run
$ dart fix --apply
More information can be found on the Dart Fix page from the Official Dart Documentation website.
Execution
Unfortunately, it seems Dart and Flutter cannot create command aliases or shortcut via the pubspec.yaml to execute recurrent commands like it can be found on Mix, rebar3 or even npm. In this case, using a Makefile can do the job. Here the one created for my project:
# GNU Makefile
EMULATOR_ANDROID ?= NameOfTheAndroidEmulator
.PHONY += all
all: test run-android
.PHONY += format
format:
dart format .
.PHONY += analyze
analyze:
flutter analyze .
.PHONY += test
test: format analyze
flutter test
.PHONY += run-android
run-android:
flutter emulators --launch $(EMULATOR_ANDROID)
.PHONY: $(.PHONY)
To format the code:
$ make format
To analyze the code:
$ make analyze
To test the code:
$ make test
Github pre-commit Hook
Before doing a git commit, it is also nice to check if everything is correct. Here a short script to execute the previous command:
$ touch .git/hooks/pre-commit
$ chmod +x .git/hooks/pre-commit
$ cat > .git/hooks/pre-commit <<EOF
#!/bin/sh
set -e
make test
EOF
Have fun and happy hacking!
Cover Image by Foto Micha on Unsplash
Top comments (0)