Answer
Overview
Flutter/Dart supports automatic code formatting on save through IDE settings and the
text
dart formatVS Code — Format on Save
json// .vscode/settings.json (project-specific) or User Settings { "editor.formatOnSave": true, "[dart]": { "editor.defaultFormatter": "Dart-Code.dart-code", "editor.formatOnSave": true } }
Or via VS Code settings UI:
text1. Ctrl+Shift+P → Open Settings (JSON) 2. Add the settings above 3. File → Preferences → Settings → search "format on save" → Enable
Android Studio — Format on Save
textPreferences → Tools → Actions on Save → Check "Reformat code" → Check "Optimize imports" (optional) → Apply
Or: Preferences → Editor → Code Style → Dart → Set line length
dart format CLI
bash# Format a single file dart format lib/main.dart # Format entire lib/ directory dart format lib/ # Check formatting (exit 1 if not formatted) dart format --output=none --set-exit-if-changed lib/ # Format with custom line length (default: 80) dart format --line-length 120 lib/
In pubspec / analysis_options
yaml# analysis_options.yaml analyzer: errors: lines_longer_than_80_chars: ignore # Relax line length rule linter: rules: - always_declare_return_types # Enforce return types - prefer_const_constructors # Prefer const - sort_child_properties_last # style rule
Pre-commit Hook (Format Before Commit)
bash# .git/hooks/pre-commit #!/bin/sh dart format --output=none --set-exit-if-changed lib/ if [ $? -ne 0 ]; then echo "❌ Code not formatted. Run: dart format lib/" exit 1 fi
CI/CD Check (GitHub Actions)
yaml- name: Check formatting run: dart format --output=none --set-exit-if-changed .
Best Practice: Enable format-on-save in your IDE, set line length to 80 (Dart default), and add
as a CI check. This ensures all team members write consistently formatted code.textdart format