DEV Community

Cover image for Q&D: Dart/Flutter Formatter, Linter and Analyzer
Mathieu Kerjouan
Mathieu Kerjouan

Posted on

Q&D: Dart/Flutter Formatter, Linter and Analyzer

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
Enter fullscreen mode Exit fullscreen mode

The dart format is a shortcut for dart format write, meaning it will apply all changes by default.

$ dart format write
Enter fullscreen mode Exit fullscreen mode

More information can be available here:

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
Enter fullscreen mode Exit fullscreen mode

The same command is available with Flutter, only the output will change a bit.

$ flutter analyze
Enter fullscreen mode Exit fullscreen mode

More information can be found there:

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
Enter fullscreen mode Exit fullscreen mode
$ dart fix --apply
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

To format the code:

$ make format
Enter fullscreen mode Exit fullscreen mode

To analyze the code:

$ make analyze
Enter fullscreen mode Exit fullscreen mode

To test the code:

$ make test
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Have fun and happy hacking!


Cover Image by Foto Micha on Unsplash

Top comments (0)