Configuring Trailing Commas in Dart 3.7+
Problem: Automatic Trailing Comma Removal in Dart Formatting
Starting with Dart SDK 3.7, the formatter automatically removes trailing commas when it collapses multi-line collections into a single line. This behavior occurs even when editor.formatOnSave
or editor.formatOnType
is enabled in IDEs like VS Code or Android Studio. For example:
// Before formatting (with trailing comma)
final colors = [
Colors.red,
Colors.green,
];
// After formatting (comma removed)
final colors = [Colors.red, Colors.green];
Users reported this change feels disruptive compared to previous Dart versions, where trailing commas were preserved and influenced code formatting by creating new lines.
Solution 1: Preserve Trailing Commas (Dart 3.8+)
For Dart SDK 3.8 and later, add this configuration to your project's analysis_options.yaml
:
analyzer:
# Other analyzer settings...
formatter:
trailing_commas: preserve
TIP
After modifying analysis_options.yaml
:
- Restart your IDE
- Run
dart format .
in the terminal to apply changes - Ensure Flutter/Dart SDK is updated (
flutter upgrade
)
Solution 2: Backward-Compatible SDK Constraint
For projects using Dart 3.7 where upgrading isn't feasible, modify pubspec.yaml
to use a broader SDK range:
environment:
sdk: ">=3.6.0 <4.0.0" # Replace "^3.7.0"
WARNING
This workaround reverts to pre-3.7 formatting behavior but may prevent accessing newer Dart features. Prefer Solution 1 if you can upgrade to Dart 3.8+.
Why This Happens
The Dart 3.7 formatter introduced logic to automatically manage trailing commas:
- Collections spanning multiple lines get a trailing comma added
- Collections collapsing to one line get the trailing comma removed
This change (based on formal proposal #1253) standardized collection formatting. Unlike other solutions, adjusting page_width
in analysis_options.yaml
does not affect trailing comma behavior. The preserve
option (added in Dart 3.8) overrides this automation.
Key Takeaways
- Use
trailing_commas: preserve
for Dart 3.8+ (recommended solution) - Use broader SDK constraints as a temporary workaround
- The behavior is intentional and matches official formatting guidelines
- Upgrade Flutter/Dart SDK for access to the latest configuration options