Skip to content

Instantly share code, notes, and snippets.

@mg
Last active July 13, 2025 12:36
Show Gist options
  • Select an option

  • Save mg/0bededf86b6086ded166619e5d715b61 to your computer and use it in GitHub Desktop.

Select an option

Save mg/0bededf86b6086ded166619e5d715b61 to your computer and use it in GitHub Desktop.
flutter cli: hot reload on file save
#!/bin/bash
# Flutter Hot Reload Script
# Usage: ./flutter-hot-reload.sh [-d device_id] [-w watch_dir]
# depends on fswatch
# Default values
DEVICE=""
WATCH_DIR="lib/"
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-d|--device)
DEVICE="$2"
shift 2
;;
-w|--watch)
WATCH_DIR="$2"
shift 2
;;
-h|--help)
echo "Usage: $0 [-d device_id] [-w watch_directory]"
echo " -d, --device Device ID (e.g., emulator-5554)"
echo " -w, --watch Directory to watch for changes (default: lib/)"
echo " -h, --help Show this help message"
exit 0
;;
*)
echo "Unknown option: $1"
echo "Use -h for help"
exit 1
;;
esac
done
# Check if we're in a Flutter project
if [ ! -f "pubspec.yaml" ]; then
echo "Error: Not in a Flutter project directory (no pubspec.yaml found)"
exit 1
fi
# Check if watch directory exists
if [ ! -d "$WATCH_DIR" ]; then
echo "Error: Watch directory '$WATCH_DIR' does not exist"
exit 1
fi
# Build flutter run command
FLUTTER_CMD="flutter run"
if [ -n "$DEVICE" ]; then
FLUTTER_CMD="$FLUTTER_CMD -d $DEVICE"
fi
echo "Starting Flutter with hot reload..."
echo "Device: ${DEVICE:-"default"}"
echo "Watching: $WATCH_DIR"
echo "Press Ctrl+C to stop"
echo
# Start flutter run in background
$FLUTTER_CMD &
FLUTTER_PID=$!
# Function to cleanup on exit
cleanup() {
echo
echo "Stopping Flutter..."
kill $FLUTTER_PID 2>/dev/null
exit 0
}
# Set up signal handlers
trap cleanup SIGINT SIGTERM
# Watch for file changes and send 'r' to flutter process
fswatch -o "$WATCH_DIR" | while read f; do
echo "Files changed, hot reloading..."
echo "r" > /proc/$FLUTTER_PID/fd/0 2>/dev/null || {
# If /proc method fails, try alternative approach
kill -USR1 $FLUTTER_PID 2>/dev/null
}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment