dart format) automatically formats Dart code according to the official Dart style guide, ensuring consistent code style across your project.
Overview
The formatter applies a consistent, opinionated style to Dart code:- Standard indentation (2 spaces)
- Line length limit (80 characters by default)
- Proper spacing and line breaks
- Consistent brace placement
Usage
Basic Examples
Command-Line Options
Output Options
Control how formatted code is displayed:Line Length
Set the maximum line length:Indentation
Configure indentation:File Selection
Exit Codes
Control exit behavior:Formatting Behavior
Before and After
Long Lines
The formatter automatically wraps long lines:Method Chains
Collections
Controlling Formatting
Disable Formatting
Disable formatting for specific code:Format Control Comments
CI/CD Integration
GitHub Actions
.github/workflows/format.yml
Pre-commit Hook
.git/hooks/pre-commit
Makefile Integration
Makefile
IDE Integration
VS Code
Enable format on save:.vscode/settings.json
IntelliJ IDEA / Android Studio
- Go to Preferences → Languages & Frameworks → Dart
- Check Format code on save
- Set Right margin (columns) to 80
Command-line Formatting
Format before committing:Output Formats
Default Output
JSON Output
Machine-Readable Output
Exit Codes
0- Success (all files formatted or already formatted)1- Files need formatting (when using--set-exit-if-changed)2- Usage error (invalid arguments)
Configuration
Project-Level Configuration
While the formatter doesn’t have a configuration file, you can document your preferences:.dart_format
scripts/format.sh
Makefile Helper
Makefile
Best Practices
1. Format Early and Often
Format code before committing:2. Automate Formatting
Use pre-commit hooks or IDE integration to format automatically.3. Consistent Line Length
Choose a line length and stick with it across your project:4. CI/CD Enforcement
Fail builds if code isn’t formatted:5. Team Agreement
Document your formatting preferences in your project README.Examples
Format Entire Project
Verify Formatting in CI
ci_check.sh
Format Specific Files
Troubleshooting
Formatter Not Found
Ensure you have Dart SDK installed:Files Not Being Formatted
Check that files have.dart extension and are valid Dart code.
Unexpected Formatting
The formatter follows the Dart style guide. If you find unexpected behavior, it’s usually intentional based on style guidelines.See Also
- Dart Style Guide - Official style recommendations
- Effective Dart - Best practices for Dart code
- dart_style package - The underlying formatting library