Flutter + auto hot reload/restart in console (CLI)

Flutter in CLI (mainly flutter run) cannot auto hot reload by itself in Linux, so we need to setup some commands to trigger it.

The basic idea is to use inotifywait in inotify-tools (which is already in Debian/Ubuntu's APT repository):

inotifywait -e create,delete,modify -mr android/ lib/ | awk "{system(\"test -e .git/flutter-run.pid && pkill -USR1 -F .git/flutter-run.pid\")}" &

Then ask flutter run to generate a pidfile. Also in my case I use FVM to manage Flutter versions:

fvm flutter run --pid-file .git/flutter-run.pid -t lib/main.dart; pkill -f '[i]notifywait'

Combine them in GNUmakefile:

#
FLUTTER?=       fvm flutter
FLUTTER_RUN_PIDFILE?=   .git/flutter-run.pid

#
run::
        inotifywait -e create,delete,modify -mr android/ lib/ | awk "{system(\"test -e ${FLUTTER_RUN_PIDFILE} && pkill -USR1 -F ${FLUTTER_RUN_PIDFILE}\")}" &
        ${FLUTTER} run --pid-file "${FLUTTER_RUN_PIDFILE}" -t lib/main.dart; pkill -f '[i]notifywait'

We can also add another inotifywait in background to trigger -USR2 (restart), but so far I feel well for -USR1 (reload).

Leave a comment

Your email address will not be published. Required fields are marked *